neoflash neoflash - 1 year ago 62
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

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
between the
of 20 and 24
. 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 == 'Male' && item.age > 19 && item.age < 25 && item.isSingle;

Imperative approach:

var count = 0;
input.forEach(function(item) {
    if ( == 'Male' && item.age > 19 && item.age < 25 && item.isSingle) count++;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download