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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With