function diffArray(arr1, arr2) {
return arr1.concat(arr2)
.filter((x, y, arr) => arr.filter(a => a === x).length === 1)
}
arr1.concat(arr2) ->concat the arr1 and arr2
.filter(x,y,arr) -> x is the every element of concatenated array , y is index , arr is name of concatenated array?
=>arr.filter(a=>a===x) ->this will check if a === x it will return true
.length->?
arr references the array being filtered, which in this case will be the combined array. See here
So when we do arr.filter(a=>a===x).length === 1. What we’re saying is, make a new array with only the elements that match x variable, i.e the current element being checked. If the length of that array is 1, i.e. only one of those elements exists in the combined array, then included it in the outer filtered array.
Here’s an easy example:
const arr1 = [1];
const arr2 = [1, 2];
arr1.concat(arr2) // [1, 1, 2]
// loop 1
.filter((x, y, arr) => // x = 1, y = 0, arr = [1,1,2]
arr.filter(a => a === x) // return = [1, 1]
.length === 1 // return = false. Element not included in final array
// loop 2
.filter((x, y, arr) => // x = 1, y = 1, arr = [1,1,2]
arr.filter(a => a === x) // return = [1, 1]
.length === 1 // return = false. Element not included in final array
// loop 3
.filter((x, y, arr) => // x = 2, y = 2, arr = [1,1,2]
arr.filter(a => a === x) // return = [2]
.length === 1 // return = true. Element included in final array
So the only element that passes is 2 because it is only in arr2 and when combined with arr1, won’t be “duplicated”.