Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js find unique values in array of objects; Return unique items and their count

I am using _underscore.js to find all unique items in an array, but I can't figure out how to also get the number of unique items returned.

_PERSONARRAY = [{name:"tom",age:7}{name:"john",age:9}{name:"becky",age:2}{name:"sam",age:7}]  _UNIQUEAGEARRAY = _.chain(_PERSONARRAY).map(function(person) { return person.age }).uniq().value(); 

In this case _UNIQUEAGEARRAY will equal:

[7,9,2] 

What I actually need returned is something like:

[{uniqueAge:7,numberOfPeople:2}{uniqueAge:9,numberOfPeople:1}{uniqueAge:2,numberOfPeople:1}] 

Thanks for help. Also, I'm assuming _underscore.js is quick at doing this?? If it's stupid slow tell me cause I'd be open to other solutions.

like image 639
That1guyoverthr Avatar asked Oct 09 '13 00:10

That1guyoverthr


1 Answers

A nice solution is to use the optional iterator function to underscore's uniq function:

let people = [   {name: "Alice", age: 21},    {name: "Bob", age: 34},   {name: "Caroline", age: 21} ]; _.uniq(people, person => person.age); 

Docs: http://underscorejs.org/#uniq

like image 118
jakecraige Avatar answered Oct 06 '22 20:10

jakecraige