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

Viewed 4416

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!

2 Answers
Related