在javascript中删除重复的对象数组对

时间:2014-12-23 17:46:39

标签: javascript arrays underscore.js lodash

Fiddle Example

我有一个像这样的对象数组:

var bigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}],
  [ { name: 'XYZ',id: 545},{ name: 'ABC',id: 391}],
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}]
];

如何删除ID为545391的任何重复对象,以将数组缩减为:

var newbigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}]
];

我想过通过制作一个新的数组列表来过滤掉重复的对:

[{391: 391,545: 545},{390: 390,545: 545}]

然后迭代它并bigarr构建newbigarr,但我的代码甚至无法创建该列表。

var test_id = [];
for(var i = 0;i < bigarr.length;i++)
{
   var value_obj = {};
   for(var j in bigarr[i])
   {
     var value = bigarr[i][j]["id"];  
     value_obj[value] = value;
   }
   test_id.push(value_obj);
}

console.log(test_id);

我使用lodash,所以欢迎任何涉及lodash的解决方案。

4 个答案:

答案 0 :(得分:1)

如果您使用下划线,您可以执行以下操作:

var bigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}],
  [ { name: 'XYZ',id: 545},{ name: 'ABC',id: 391}],
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}]
];

console.log(_.uniq(bigarr,function(item){
    return [
        [item[0].id+item[0].name],
        [item[1].id+item[1].name]
    ].sort().toString()
}))

编辑:仅当您始终拥有一对具有id和字符串名称的对象时才有效。不检查深化的对象或其他键

答案 1 :(得分:1)

JSFIDDLE

如果您使用的是纯粹的js,那么只需使用迭代和辅助数组来跟踪您所看到的内容,就可以这样做:

var bigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}],
  [ { name: 'XYZ',id: 545},{ name: 'ABC',id: 391}],
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}]
];

var seen = [];
var final = [];

for(i = 0; i < bigarr.length; i++){
    var unseen = true;
    for(j = 0;j<seen.length;j++){
        if((seen[j][0] == bigarr[i][0].id && seen[j][1] == bigarr[i][1].id) || (seen[j][0] == bigarr[i][1].id && seen[j][1] == bigarr[i][0].id)
          ){
            unseen = false;
        }
    }
    if(unseen){
        final.push(bigarr[i]);
        seen.push([bigarr[i][0].id, bigarr[i][1].id]);
    }
}

答案 2 :(得分:1)

使用Lo-Dash。 JSFiddle

var bigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}],
  [ { name: 'XYZ',id: 545},{ name: 'ABC',id: 391}],
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}]
];

var seenIds = {};
var nodup = _.filter(bigarr, function(pair) {
    var ids = [pair[0].id, pair[1].id].sort();
    if(seenIds[ids]) {
        return false;
    } else {
        seenIds[ids] = true;
        return true;
    }
});

答案 3 :(得分:1)

使用lo-dash(jsFiddle)的一行解决方案:

var bigarr = 
[ 
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}],
  [ { name: 'EFG',id: 390},{ name: 'XYZ',id: 545}],
  [ { name: 'XYZ',id: 545},{ name: 'ABC',id: 391}],
  [ { name: 'ABC',id: 391},{ name: 'XYZ',id: 545}]
];  

_.uniq(bigarr, function(a) { return _.pluck(a, 'id').sort() + '' });