Diff Two Arrays - cleaner code?

Tell us what’s happening:
I’m wondering if anyone can help me make this code cleaner. Thanks!

Your code so far


function diffArray(arr1, arr2) {
var newArr = [];

arr2.filter(num => {
if( arr1.indexOf(num) === -1){
  newArr.push(num)
}
});

arr1.filter(num => {
if(arr2.indexOf(num) === -1){
if(newArr.indexOf(num) === -1){
newArr.push(num)
}}
});
console.log(newArr)
return newArr;
}

diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36.

Challenge: Diff Two Arrays

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays

Since filter() function filters an array according to the condition and return new array so you store the new array in new variable like this

var arr3=arr2.filter(num => arr1.indexOf(num) === -1);

do the same for second filter() i.e.

var arr4 =arr1.filter(num =>arr2.indexOf(num) === -1);

and finaly join both arrays value using newArr i.e.

newArr=[...a,...ne];

and then return newArr i.e.

return newArr;
1 Like