比较两个对象数组javascript并使用下划线或lodash将不匹配的数组元素抛出到新数组中

时间:2017-02-27 21:32:30

标签: javascript angularjs arrays lodash

我有两个数组apple = [1,5,10,15,20]bottle = [1,5,10,15,20,25]使用lodash或任何javascript函数,我想要一个包含唯一元素c= [25]的数组c。更确切地说,当'apple'数组与'bottle'数组进行比较时,我想要所有元素的列表,以显示唯一的元素/

2 个答案:

答案 0 :(得分:1)

您可以使用reduce()filter()为此创建自己的功能。



var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

function diff(a1, a2) {
  //Concat array2 to array1 to create one array, and then use reduce on that array to return
  //one object as result where key is element and value is number of occurrences of that element
  var obj = a1.concat(a2).reduce(function(result, element) {
    result[element] = (result[element] || 0) + 1
    return result
  }, {})
  
  //Then as function result return keys from previous object where value is == 1 which means that
  // that element is unique in both arrays.
  return Object.keys(obj).filter(function(element) {
    return obj[element] == 1
  })
}

console.log(diff(apple, bottle))




具有ES6箭头功能的相同代码的较短版本。



var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

function diff(a1, a2) {
  var obj = a1.concat(a2).reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {})
  return Object.keys(obj).filter(e => obj[e] == 1)
}

console.log(diff(apple, bottle))




答案 1 :(得分:1)

您可以将Array#filter与相反数组的Set一起使用。

此提案使用complement函数,如果元素a不在集合b中,则返回true

对于对称差异,必须对双方使用带回调的过滤。



function getComplement(collection) {
    // initialize and close over a set created from the collection passed in
    var set = new Set(collection);
    // return iterator callback for .filter()
    return function (item) {
        return !set.has(item);
    };
}
var apple = [1,5,10,15,20], 
    bottle = [1,5,10,15,20,25],
    unique = [
        ...apple.filter(getComplement(bottle)),
        ...bottle.filter(getComplement(apple))
    ];

console.log(unique);