Sunday, May 19, 2024
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 49955  / 11 Years ago, wed, october 9, 2013, 12:00:00

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.


More From » underscore.js

 Answers
124

I think you're looking for the countBy function:



_UNIQUEAGEARRAY = _.countBy(_PERSONARRAY, age);


It produces the result:



{2:1,7:2,9:1}


JSFiddle demo: http://jsfiddle.net/4J2SX/


[#75133] Tuesday, October 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;