问题
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/
回答1:
You could use Array#filter with a Set of the opposite array.
This proposal uses a complement function which returns true if the element a is not in the set b.
For a symmetric difference, the filtering with callback has to be used for both sides.
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);
回答2:
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))
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))
来源:https://stackoverflow.com/questions/42496158/compare-two-array-of-objects-javascript-and-throw-the-unmatched-array-elements-i