neoflash neoflash - 1 year ago 53
Javascript Question

Filter an array of object in javascript

I've been trying for two hours to figure this out and have found some articles related to my question but I can't seem to make the suggestions work in my situation. So I hope you can help.

I have an array of objects called

personArray
with 50 000 entries, here are two sample entries:

[
{ sex: "Male",
lastName: "DIXON",
firstName: "Esteban",
age: 51,
isSingle: true
},
{
sex: "Female",
lastName: "BULLOCK",
firstName: "Daniela",
age: 58,
isSingle: false
}
]


I want to be able to get useful demographic information out of that data. For instance, I would like to know how many
Male
between the
age
of 20 and 24
isSingle
. How do I do that?

As mentioned, I have read other related answers but, being rather new at this, have been unable to translate them to my particular situation. I'm not looking to find a single object, or a single value of a property of a single object. I'm looking to find how many entries out of the 50 000 fit the parameters mentioned above.

Answer Source

Functional approach:

var count = input.filter(function(item) {
    return item.sex == 'Male' && item.age > 19 && item.age < 25 && item.isSingle;
}).length;

Imperative approach:

var count = 0;
input.forEach(function(item) {
    if (item.sex == 'Male' && item.age > 19 && item.age < 25 && item.isSingle) count++;
});