我使用_underscore.js查找数组中的所有唯一项,但我无法弄清楚如何获取返回的唯一项数。
_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();
在这种情况下,_UNIQUEAGEARRAY将等于:
[7,9,2]
我实际需要的东西是:
[{uniqueAge:7,numberOfPeople:2}{uniqueAge:9,numberOfPeople:1}{uniqueAge:2,numberOfPeople:1}]
感谢您的帮助。另外,我假设_underscore.js很快就这样做了?如果这是愚蠢的慢,告诉我因为我会对其他解决方案持开放态度。
答案 0 :(得分:74)
一个很好的解决方案是使用可选的迭代器函数来强调uniq
函数:
let people = [
{name: "Alice", age: 21},
{name: "Bob", age: 34},
{name: "Caroline", age: 21}
];
_.uniq(people, person => person.age);
答案 1 :(得分:16)
我认为您正在寻找countBy
功能:
_UNIQUEAGEARRAY = _.countBy(_PERSONARRAY, "age");
它产生结果:
{"2":1,"7":2,"9":1}
JSFiddle演示:http://jsfiddle.net/4J2SX/
答案 2 :(得分:1)
如果需要,可以使用下划线的groupBy(对于大型数据集可能不是一个好主意,因为它保留了所有分组项的列表)
示例:
var d = _.groupBy(_PERSONARRAY, function(p){
return p.age;
});
如果您想将其映射到您的确切格式,请尝试在groupBy之后执行地图:
var x = _.map(d, function(people, age) {
return {uniqueAge: age, numberOfPeople: people.length};
});
jsFiddle:http://jsfiddle.net/jsgkC/2/
答案 3 :(得分:0)
groupBy
功能很有用。
_personsList = [{name:"anjo",age:5},{name:"george",age:3},{name:"jack",age:5}];
_uniqAgeList = _.groupBy(_personsList, "age");
将产生输出
{
"3":[{"name":"george","age":3}],
"5":[{"name":"anjo","age":5},{"name":"jack","age":5}]
}
jsfiddle:http://jsfiddle.net/4J2SX/199/