should we consider that the same id is the same? Or is it an overall comparison? Of course, this thing is called key
anyway, so let's assume id
comparison.
introduce lodashjs
,
console.log(_.xorBy(arr1, arr, 'id'), "id")
if it is other key, such as overall comparison. So
console.log(_.xorBy(arr1, arr, function(v){return JSON.stringify(v)}),'fun')
you can do this if there are no duplicate objects in an array, although it doesn't feel very efficient
var copyArr = arr2.map(val => JSON.stringify(val))
arr1 = arr1.filter(obj => {
let index = copyArr.indexOf(JSON.stringify(obj))
if (index === -1) return true
arr2.splice(index, 1)
copyArr.splice(index, 1)
})
arr1.concat(arr2)
let intersection = arr1.filter (v = > arr2.includes (v))
arrays take intersection
you can try this:
take the complement of arr1
concat
arr2
, that is, the non-intersection of the two. The rules
after
is used to implement reusable functions. Just pass in the key
collection to check.
function filter (arr1, arr2, rules) {
return arr1.filter(item1 => !arr2.some(item2 => rules.every(key => item1[key] === item2[key])))
}
function build (arr1, arr2, rules) {
return [].concat(filter(arr1, arr2, rules), filter(arr2, arr1, rules))
}
let result = build(arr1, arr2, ['id', 'name'])
console.log(result)