Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素。换言之,返回两个数组的差异。
function diff(arr1, arr2) {
var newArr = [];
// Same, same; but different.
return newArr;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
The solution is O(n) by using hashes to keep tracking of item counts. If the item only has 1 count, that means it's unique between the two arrays.
function diff(arr1, arr2) {
var newArr = [];
var itemsCounter = {};
// get arr1's items into itemsCounter
arr1.forEach(function(item) {
if (itemsCounter[item] === undefined) {
itemsCounter[item] = 1;
} else {
itemsCounter[item]++;
}
});
// get arr2's items into itemsCounter
arr2.forEach(function(item) {
if (itemsCounter[item] === undefined) {
itemsCounter[item] = 1;
} else {
itemsCounter[item]++;
}
});
Object.keys(itemsCounter).forEach(function(key){
// if the item has only been counted once, that means that item is unique between arr1 and arr2
if (itemsCounter[key] === 1) {
newArr.push(key)
}
});
return newArr;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);