javascript Underscore.js 在对象数组中查找唯一值;返回唯一项目及其数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19261122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underscore.js find unique values in array of objects; Return unique items and their count
提问by That1guyoverthr
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.
我正在使用 _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();
In this case _UNIQUEAGEARRAY will equal:
在这种情况下 _UNIQUEAGEARRAY 将等于:
[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.
感谢帮助。另外,我假设 _underscore.js 在这方面做得很快??如果它是愚蠢的缓慢告诉我因为我愿意接受其他解决方案。
采纳答案by howrad
I think you're looking for the countBy
function:
我认为您正在寻找countBy
功能:
_UNIQUEAGEARRAY = _.countBy(_PERSONARRAY, "age");
It produces the result:
它产生的结果:
{"2":1,"7":2,"9":1}
JSFiddle demo: http://jsfiddle.net/4J2SX/
JSFiddle 演示:http: //jsfiddle.net/4J2SX/
回答by jakecraige
A nice solution is to use the optional iterator function to underscore's uniq
function:
一个不错的解决方案是使用可选的迭代器函数来强调uniq
函数:
let people = [
{name: "Alice", age: 21},
{name: "Bob", age: 34},
{name: "Caroline", age: 21}
];
_.uniq(people, person => person.age);
回答by Craig MacGregor
You can use underscore's groupBy if you want (might not be a good idea for a large dataset since it keeps a list of all the grouped items)
如果需要,您可以使用下划线的 groupBy(对于大型数据集可能不是一个好主意,因为它保留了所有分组项目的列表)
Example:
例子:
var d = _.groupBy(_PERSONARRAY, function(p){
return p.age;
});
If you want to map this to your exact format try doing a map after the groupBy:
如果您想将其映射到您的确切格式,请尝试在 groupBy 之后进行映射:
var x = _.map(d, function(people, age) {
return {uniqueAge: age, numberOfPeople: people.length};
});
jsFiddle: http://jsfiddle.net/jsgkC/2/
jsFiddle:http: //jsfiddle.net/jsgkC/2/
回答by Amil Sajeev
groupBy
function is useful.
groupBy
功能很有用。
_personsList = [{name:"anjo",age:5},{name:"george",age:3},{name:"Hyman",age:5}];
_uniqAgeList = _.groupBy(_personsList, "age");
will produce output
将产生输出
{
"3":[{"name":"george","age":3}],
"5":[{"name":"anjo","age":5},{"name":"Hyman","age":5}]
}
jsfiddle :http://jsfiddle.net/4J2SX/199/
jsfiddle:http: //jsfiddle.net/4J2SX/199/