比较两个对象javascript数组,并使用下划线或lodash将不匹配的数组元素放入新数组中 [英] compare two array of objects javascript and throw the unmatched array elements into new array using underscore or lodash

查看:74
本文介绍了比较两个对象javascript数组,并使用下划线或lodash将不匹配的数组元素放入新数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用lodash或任何javascript函数的数组apple = [1,5,10,15,20]bottle = [1,5,10,15,20,25],我想要一个具有唯一元素c= [25]的数组c.更准确地说,我希望将"apple"数组与"bottle"数组进行比较时所有元素的列表显示唯一的元素.

I have two arrays apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] using lodash or any javascript function, I want an array c with unique elements c= [25]. To be more precise, I want the list of all the elements when 'apple' array is compared with 'bottle' array, to display the elements which are unique/

推荐答案

为此,您可以使用reduce()filter()创建自己的函数.

You can create your own function with reduce() and filter() for this.

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箭头功能的更短版本的相同代码.

Shorter version of same code with ES6 arrow functions.

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))

这篇关于比较两个对象javascript数组,并使用下划线或lodash将不匹配的数组元素放入新数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆