How to count certain elements in an object array in JavaScript?

Viewed 85

I'm trying to count occurance of every element in this JSON file.

[
    {
        "firstName": "Sena",
        "lastName": "Turan",
        "age": 19,
        "retired": false
    },
    {
        "firstName": "Çınar",
        "lastName": "Turan",
        "age": 1,
        "retired": false
    },
    {
        "firstName": "Ahmet",
        "lastName": "Turan",
        "age": 55,
        "retired": true
    }
]

Like how many "firstName" or "age" variables it contains. Anyone has an opinion on this? Thanks.

4 Answers

You can reduce your array and up the count for every element in the objects of the array:

const arr = [{ "firstName" : "Sena", "lastName" : "Turan", "age" : 19, "retired" : false}, {"firstName" : "Çınar", "lastName" : "Turan", "age" : 1, "retired" : false}, {"firstName" : "Ahmet", "lastName" : "Turan", "age" : 55, "retired" : true} ];

const result = arr.reduce((acc, curr) => {
  for(let el in curr) {
    acc[el] = acc[el] == null ? 1 : acc[el] + 1;
  }
  return acc;
}, {});

console.log(result);

You could also simply go through all of the items and check for the specific item you want:

const arr = [{ "firstName" : "Sena", "lastName" : "Turan", "age" : 19, "retired" : false}, {"firstName" : "Çınar", "lastName" : "Turan", "age" : 1, "retired" : false}, {"firstName" : "Ahmet", "lastName" : "Turan", "age" : 55, "retired" : true} ];
    
const count= (it) => {
  let count = 0;
  
  for (el of arr) {
    if(el[it]) {
      count++;
    }
  }
  return count;
};
    
console.log(count("firstName"));

If I may add my attempt, this is written in ES6:

const countAppearance = key => {
    let count = 0;
    arr.forEach(record => (count += record[key] ? 1 : 0));
    return count;
};

@tunayvaz Also, one very CRUCIAL detail: all these functions don't actually check for the key itself, they check for the existence of the value of that key. Meaning, if you make all "age" undefined, it will give you 0, even though age appears in all 3 records. If you want a strictly working function, you might want to have a look at Object.keys() or something.

yourArray.filter(person => 'age' in person).length should work for the age, for an example. YOu can tweak it for other properties.

Related