# Diff Two Arrays Need Help!

Tell us what’s happening:
I have a question about the code below.

function diffArray(arr1, arr2) {
return [
...diff(arr1, arr2),
...diff(arr2, arr1)
]

function diff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
}

I understood a little bit about the code above but there is one part that makes me wonder:

return [
...diff(arr1, arr2),
...diff(arr2, arr1)
]

What is the function of the above code, what value does it return? Can someone explain me how it works, thanks.

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/78.0.136 Chrome/72.0.3626.136 Safari/537.36.

By this point in the curriculum, you should already be familiar with the “spread” operator, i.e. [...foo]. Since diff returns an array, what’s happening is it’s calling diff with the given arguments, then inserting the result into the array using the spread operator. If we were to use some temporary variables, it would look something like this:

let d1 = diff(arr1, arr2)
let d2 = diff(arr2, arr1)
return [...d1, ...d2]

So if d1 was, for example, [1,2,3], and d2 was [9,8,7], the result of [...d1, ...d2] would be [1,2,3,9,8,7].

1 Like
function diffArray(arr1, arr2) {
var newArr = [];
let longLen, shortLen = [];
if(arr1.length > arr2.length){
longLen = arr1;
shortLen = arr2;
} else{
longLen = arr2;
shortLen = arr1;
}
if(longLen.filter(function(item,index,arr){
//check unique element in longLen array element not in shortLen array element and return the value.
if(shortLen.indexOf(item) === -1){

return newArr.push(item)
// check unique element in shortLen array element not in longLen array and push the value to newArr
}
}))

if(shortLen.filter(function(item,index,arr){
//check unique element in longLen array element not in shortLen array element and return the value.
if(longLen.indexOf(item) === -1){

return newArr.push(item)
// check unique element in shortLen array element not in longLen array and push the value to newArr
}
}))
// Same, same; but different.
return newArr;
}

diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] );
IT WORKS, BUT I NEED ADVICE ON HOW TO FORMAT THIS NICELY