Diff Two Arrays - Imperative Solution

Hello! I am curious as to why my solution only seems to work halfway, in that it pushes the unique element into ‘newArr’ for one array, but not for both. I am just trying to solve it imperatively at first using ‘for’ loops, before I attempt it with a higher order function such as ‘filter’. Thus I want to figure out why this proposed solution fails. Any help would be appreciated!


function diffArray(arr1, arr2) {
var newArr = [];
for (var i = 0; i < arr1.length; i++) {
  if (arr2.indexOf(arr1[i]) === -1) {
      newArr.push(arr1[i]);
  } 
for (var i = 0; i < arr2.length; i++) {
  if (arr1.indexOf(arr2[i]) === -1) {
      newArr.push(arr2[i]);
  }
}
}
return newArr;
}

console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 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

You need to close first for loop before starting the second for loop. i.e. :
put } before the second for loop to close first for loop.and remove } you inserted before the return statement.

If you properly indent your code, it will be easier to see what statements are within each for loop code block.

1 Like

Fantastic! That was the issue. Thank you!!!