I'm writing a diff(arr1, arr2) function to compare two arrays and return a new array with any items not found in both of the original arrays.
Example:
diff([1, 2, 3, 5], [1, 2, 3, 4, 5])
// [4]
diff([1, "calf", 3, "piglet"], [7, "filly"])
// [1, "calf", 3, "piglet", 7, "filly"]
My solution is to build an object using the unique value in the array as the key, and the frequency as the value to that key. Then I collect the key whose value is 1 into a new array.
Problem: I think the fact that key is treated as a string in object makes my solution not very elegant, because I will need to use Number() to convert an "integer" key from string to number.
Question: my code works but does anyone have a better solution to find unique values after comparing 2 arrays?
My code:
function diff(arr1, arr2) {
var newArr = arr1.concat(arr2);
var dict = {};
for (var i = 0; i < newArr.length; i++) {
if (!dict[newArr[i]]) {
dict[newArr[i]] = 1;
}
else {
dict[newArr[i]]++;
}
}
var unique = [];
for (var key in dict) {
if (dict[key] === 1) {
if (!Number(key)) {
unique.push(key);
}
else {
unique.push(Number(key));
}
}
}
return unique;
}
Thanks for your help =)