Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of occurrences of distinct values from an array of objects in Javascript?

I have an array of objects like below:

var array =
    [
        {"name":"abc","age":20}
        {"name":"abc","age":20}
        {"name":"abc","age":20}
        {"name":"xyz","age":21}
        {"name":"xyz","age":21}
    ]

I want to count the number of occurrences of distinct values like:

[3,2]

Assuming abc has 3 occurrences and xyz has 2 occurrences.

I am doing it in reactjs. I am able to get distinct values like [abc,xyz] using this answer.

ES6 syntax is preferred.

like image 844
Triyugi Narayan Mani Avatar asked Apr 28 '17 06:04

Triyugi Narayan Mani


3 Answers

You'll need to know to which name a count belongs, so I propose not to output an array that gives you no clue about that, but an object keyed by names and with as value the corresponding count:

var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );

var array =
    [
        {"name":"abc","age":20},
        {"name":"abc","age":20},
        {"name":"abc","age":20},
        {"name":"xyz","age":21},
        {"name":"xyz","age":21}
    ];
    
var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );

console.log(result);
like image 197
trincot Avatar answered Nov 27 '22 12:11

trincot


Map/Reduce to the rescue:

const frequency = array
  .map(({ name }) => name)
  .reduce((names, name) => {
    const count = names[name] || 0;
    names[name] = count + 1;
    return names;
  }, {});

// frequency: { abc: 3, xyz: 2 }
like image 34
Norguard Avatar answered Nov 27 '22 14:11

Norguard


You can use forEach/map to iterate the array and store the count in another variable, Check this:

var array = [
     {"name" : "abc", "age" : 20},
     {"name" : "abc", "age" : 20},
     {"name" : "abc", "age" : 20},
     {"name" : "xyz", "age" : 21},
     {"name" : "xyz", "age" : 21},
];
    
let b = {};

array.forEach(el => {
    b[el.name] = (b[el.name] || 0) + 1;
})

console.log(b);
like image 45
Mayank Shukla Avatar answered Nov 27 '22 13:11

Mayank Shukla