比较两个数组的对象JavaScript,然后使用下划线或Lodash将无与伦比的数组元素扔到新数组中



我有两个数组apple = [1,5,10,15,20]bottle = [1,5,10,15,20,25]使用Lodash或任何JavaScript函数,我想要一个具有唯一元素c= [25]的数组C。更确切地说,我想要将"苹果"数组与"瓶子"数组进行比较时的所有元素的列表,以显示唯一的元素/

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

此提案使用一个补体功能,如果元素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);

您可以使用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))

最新更新