This content originally appeared on DEV Community and was authored by Muhmmad Awd
DESCRIPTION:
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.
Examples
[1, 2, 3, 5], [1, 2, 3, 4, 5]
// should return [4].
[1, "calf", 3, "piglet"], [1, "calf", 3, 4]
// should return ["piglet", 4].
My approach for solving this problem:
- concat the 2 arrayes.
- add every item into new obj
- if it's unquie get vlaue of 1 and get 2 if it's not.
- if not return sliced str with num length.
- filter item with value of 1 then map the number.
My solution:
function diffArray(arr1, arr2) {
let newArr = arr1.concat(arr2)
let numObj = {}
newArr.forEach((item)=>{
numObj[item] = numObj[item] ? numObj[item] +1:1
})
return Object.keys(numObj)
.filter((item)=>{
return numObj[item] == 1
})
.map((num)=>{
if(!isNaN(num)){
return +num
}
return num
})
}
diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
freeCodeCamp approach for solving this problem:
- concat the 2 arrays.
- filter if item includes in arr1 or arr2 and return him.
freeCodeCamp solution:
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!
Follow Muhmmad Awd on
If you have any questions or feedback, please feel free to contact me at
This content originally appeared on DEV Community and was authored by Muhmmad Awd

Muhmmad Awd | Sciencx (2023-05-10T18:02:10+00:00) Diff form Two Arrays. Retrieved from https://www.scien.cx/2023/05/10/diff-form-two-arrays/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.