Javascript Underscore.js,根据键值删除对象数组中的重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28991014/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:42:42  来源:igfitidea点击:

Underscore.js, remove duplicates in array of objects based on key value

javascriptarraysobjectduplicatesunderscore.js

提问by nikoshr

I have the following JS array:

我有以下 JS 数组:

var myArray = [{name:"Bob",b:"text2",c:true},
               {name:"Tom",b:"text2",c:true},
               {name:"Adam",b:"text2",c:true},
               {name:"Tom",b:"text2",c:true},
               {name:"Bob",b:"text2",c:true}
               ];

I want to eliminate the indexes with name value duplicates and recreate a new array, with distinct names, eg:

我想消除名称值重复的索引并重新创建一个具有不同名称的新数组,例如:

var mySubArray = [{name:"Bob",b:"text2",c:true},
                  {name:"Tom",b:"text2",c:true},
                  {name:"Adam",b:"text2",c:true},
                 ];

As you can see, I removed "Bob" and "Tom", leaving only 3 distinct names. Is this possible with Underscore? How?

如您所见,我删除了“Bob”和“Tom”,只留下了 3 个不同的名字。下划线可以做到这一点吗?如何?

回答by nikoshr

With Underscore, use _.uniqwith a custom transformation, a function like _.property('name')would do nicely or just 'name', as @Gruff Bunny noted in the comments :

使用Underscore_.uniq与自定义转换一起使用,就像@Gruff Bunny 在评论中指出的那样,像_.property('name')这样的函数会做得很好或只是'name'

var mySubArray = _.uniq(myArray, 'name');

And a demo http://jsfiddle.net/nikoshr/02ugrbzr/

还有一个演示http://jsfiddle.net/nikoshr/02ugrbzr/

If you use Lodashand not Underscore, go with the example given by @Jacob van Lingen in the comments and use _.uniqBy:

如果您使用Lodash而不是Underscore,请使用@Jacob van Lingen 在评论中给出的示例并使用_.uniqBy

var mySubArray = _.uniqBy(myArray, 'name')

回答by Dexygen

The other answer is definitely best but here's another that's not much longer that also exposes you to more underscore method's, if you're interested in learning:

另一个答案绝对是最好的,但如果您有兴趣学习,这里还有一个不会太长的答案,它也会让您接触更多下划线方法:

var mySubArray = []

_.each(_.uniq(_.pluck(myArray, 'name')), function(name) {
    mySubArray.push(_.findWhere(myArray, {name: name}));
})