Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new array from existing one only with elements that contain specific value

I create a new array from an existing one (big array with 100.000 objects). In the new array I want only elements where the value of "city" is for example New York City.

    var newData = [];

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude": 
            data[i].longitude, "latitude": data[i].latitude, "state": 
            data[i].state};

        }
     }

I must be doing something wrong since a lot of elements in the new array are null

The new array then looks something like this:

[null,null,null,null,null, {"city":"New York", "logitude": 
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude": 
-73.935242, "latitude": 40.730610, "state": "NY"}]

What am I doing wrong? How could I achieve my goal?

Thanks in advance guys!

like image 437
Unknown User Avatar asked Oct 22 '25 14:10

Unknown User


1 Answers

The elements won't be null, they'll be missing (which shows up as undefined when you try to access them). The reason is that you're increasing i every time, even when you skip an entry.

To fix it, use push instead:

var newData = [];

for (var i = 0; i < data.length; i++) {

    if (data[i].city === "New York City") {
        newData.push({
            "city": data[i].city,
            "longitude": data[i].longitude,
            "latitude": data[i].latitude,
            "state": data[i].state
        });
    }
}

If you want the two arrays to share objects, you could use filter instead:

var newData = data.filter(function(entry) {
    return entry.city === "New York City";
});

but if you want the new array to have new objects that are different from the originals, your for loop is fine.

like image 54
T.J. Crowder Avatar answered Oct 24 '25 03:10

T.J. Crowder