在Javascript中从对象数组中删除公共对象的最佳方法

时间:2015-01-08 14:03:54

标签: javascript

我有以下对象数组

a = [{c:1, r:2}, {c:2, r:2}, {c:3, r:2}]
b = [{c:1, r:1}, {c:2, r:2}, {c:3, r:3}]

现在我要删除这个常见对象,

Like var result = removeCommon(a, b);
Output result = [{c:1, r:2}, {c:2, r:2}, {c:3, r:2}, {c:1, r:1}, {c:3, r:3}]

我需要最好的方法,因为数组大小很大

2 个答案:

答案 0 :(得分:2)

我找到了解决方法

_.uniq(a.concat(b), function(array){
    return "c:" + array.c + "r:" + array.r;
})

result : [{c:1, r:2}, {c:2, r:2}, {c:3, r:2}, {c:1, r:1}, {c:3, r:3}]

答案 1 :(得分:2)

我的解决方案(没有外部库):

var a = [{c:1, r:2}, {c:2, r:2}, {c:3, r:2}];
var b = [{c:1, r:1}, {c:2, r:2}, {c:3, r:3}];
var c = removeCommon(a, b);

console.log(c);

function removeCommon(a, b) {
  var result = {};

  a.concat(b).forEach(function (i) {
    result['c' + i.c + 'r' + i.r] = i;
  });

  return Object.keys(result).map(function (k) {
    return result[k];
  });
}

a fiddle