使用Underscore for Javascript删除重复的对象

plu*_*us- 122 javascript json underscore.js

我有这种数组:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
Run Code Online (Sandbox Code Playgroud)

我想过滤它有:

var bar = [ { "a" : "1" }, { "b" : "2" }];
Run Code Online (Sandbox Code Playgroud)

我尝试使用_.uniq,但我想因为{ "a" : "1" }它不等于它自己,它不起作用.有没有办法为underscore uniq提供overriden equals函数?

Sha*_*mal 231

.uniq / .unique接受回调

var list = [{a:1,b:5},{a:1,c:5},{a:2},{a:3},{a:4},{a:3},{a:2}];

var uniqueList = _.uniq(list, function(item, key, a) { 
    return item.a;
});

// uniqueList = [Object {a=1, b=5}, Object {a=2}, Object {a=3}, Object {a=4}]
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 用于比较的回调返回值
  2. 具有唯一返回值的第一个比较对象用作唯一
  3. underscorejs.org演示没有回调用法
  4. lodash.com显示用法

另一个例子: 使用回调从列表中提取汽车品牌颜色

  • Iterator听起来不是一个好名字,它是一个类似哈希的函数,用于确定每个对象的身份 (2认同)

小智 38

如果您要根据ID删除重复项,可以执行以下操作:

var res = [
  {id: 1, content: 'heeey'},
  {id: 2, content: 'woah'}, 
  {id: 1, content:'foo'},
  {id: 1, content: 'heeey'},
];
var uniques = _.map(_.groupBy(res,function(doc){
  return doc.id;
}),function(grouped){
  return grouped[0];
});

//uniques
//[{id: 1, content: 'heeey'},{id: 2, content: 'woah'}]
Run Code Online (Sandbox Code Playgroud)


Lar*_*tle 17

实施Shiplu的答案.

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

var x = _.uniq( _.collect( foo, function( x ){
    return JSON.stringify( x );
}));

console.log( x ); // returns [ { "a" : "1" }, { "b" : "2" } ]
Run Code Online (Sandbox Code Playgroud)


tux*_*ear 15

当我有一个属性id时,这是我在下划线中的优先方式:

var x = [{i:2}, {i:2, x:42}, {i:4}, {i:3}];
_.chain(x).indexBy("i").values().value();
// > [{i:2, x:42}, {i:4}, {i:3}]
Run Code Online (Sandbox Code Playgroud)


Aqi*_*taz 11

使用下划线唯一的 lib跟随我的工作,我在_id的基础上使列表唯一,然后返回_id的String值:

var uniqueEntities = _.uniq(entities, function (item, key, a) {
                                    return item._id.toString();
                                });
Run Code Online (Sandbox Code Playgroud)


Jos*_*ick 10

这是一个简单的解决方案,它使用深层对象比较来检查重复项(不需要转换为JSON,这是低效和hacky)

var newArr = _.filter(oldArr, function (element, index) {
    // tests if the element has a duplicate in the rest of the array
    for(index += 1; index < oldArr.length; index += 1) {
        if (_.isEqual(element, oldArr[index])) {
            return false;
        }
    }
    return true;
});
Run Code Online (Sandbox Code Playgroud)

如果它们在数组中稍后有重复,它会过滤掉所有元素 - 这样就可以保留最后一个重复元素.

测试重复使用_.isEqual,在两个对象之间执行优化的深度比较,请参阅下划线isEqual文档以获取更多信息.

编辑:更新使用_.filter哪种是更清洁的方法


Rya*_*inn 8

lodash 4.6.1 docs将此作为对象键相等的示例:

_.uniqWith(objects, _.isEqual);

https://lodash.com/docs#uniqWith


Iva*_*anM 7

尝试迭代器功能

例如,您可以返回第一个元素

x = [['a',1],['b',2],['a',1]]

_.uniq(x,false,function(i){  

   return i[0]   //'a','b'

})
Run Code Online (Sandbox Code Playgroud)

=> [['a',1],['b',2]]