Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  180] [ 4]  / answers: 1 / hits: 16535  / 7 Years ago, fri, april 28, 2017, 12:00:00

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.


More From » arrays

 Answers
11

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);




[#57978] Wednesday, April 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;