1

I have an array like this:

var obj = {
    "people": [{
        "id": "100",
        "name": "name 1",
        "desc": "desc 1",
        "class": "a"
    }, {
        "id": "192",
        "name": "name 2",
        "desc": "desc 2",
        "class": "b"
    }, {
        "id": "324",
        "name": "name 3",
        "desc": "desc 3",
        "class": "b"
    }, {
        "id": "324",
        "name": "name 4",
        "desc": "desc 4",
        "class": "a"
    }, {
        "id": "324",
        "name": "name 5",
        "desc": "desc 5",
        "class": "a"
    }]
};

I know that for example, in order to get all the records with class "a" I do this:

obj.people.filter(function(item) { return item.class === "a" });

But How can I count to total number of records that contain class "a" ?

2 Answers 2

1

You could use the Array#length property from the returned array.

count = obj.people.filter(function(item) { return item.class === "a" }).length;

Or use Array#reduce and add the comparison.

count = obj.people.reduce(function (r, item) { return r + +(item.class === "a") }, 0);
Sign up to request clarification or add additional context in comments.

Comments

0

Just check the length of array returned by the filter

var result = obj.people.filter(function(item) { return item.class === "a" });
console.log( result.length );

or you can simply run a loop that tells you this count

var count = 0;
for( var counter = 0; counter < obj.people.length; counter++ )
{
   ( obj.people[ counter ].class === "a" ) && count++;
}
console.log( count );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.