# A Better Solution? - Diff Two Arrays

A Better Solution? - Diff Two Arrays
0
#1

Intermediate Algorithm Scripting: Diff Two Arrays

Hi All,

Just completed the “Diff Two Arrays” exercise in Intermediate Algorithm Scripting and was hoping someone out there might have some pointers on achieving a more elegant solution than my one below.

Whilst I feel like my solution holds up well in terms of functionality, I can’t help but feel like multiple for loops seems a bit messy I don’t know where I feel like I’ve heard/seen this, but I’m under the impression that for loops should be avoided where possible.

0 Likes

#2

Ignore the above… Just stumbled upon this post…

https://forum.freecodecamp.org/t/freecodecamp-algorithm-challenge-guide-diff-two-arrays/16008

0 Likes

#3

Here is a shorter version.

``````function diffArray(arr1, arr2) {
var newArr = arr1.concat(arr2);
// Same, same; but different.
return  newArr.filter(x=>arr1.indexOf(x)===-1 || arr2.indexOf(x)===-1)

}
``````
4 Likes

#4

Hello Guys . This is my solution

``````function diffArray(arr1, arr2) {
var newArr = arr1.filter(x => arr2.indexOf(x) < 0).concat(arr2.filter(x => arr1.indexOf(x) < 0));
return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
``````
1 Like

#5

Great, simple solution man!

0 Likes

#6

This is my solution. It is not the shortest way but I tried to make it more functional.

[p]

``````function diffArray(arr1, arr2) {
var newArr = [];
let comp = function(arrX,arrY){
arrX.forEach((x) => {
if(!arrY.includes(x)) newArr.push(x);
});
};
comp(arr1,arr2);
comp(arr2,arr1);
return newArr;
}
``````

[/p]

0 Likes

closed #7
0 Likes