2

I am learning JavaScript via FREECODECAMP.


Here is what I am asked to do:

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

Note
You can return the array with its elements in any order.


Here is what I did, it works, and passes the tests:

function diffArray(arr1, arr2) {
  let newArr = [].concat(arr1.filter(item => {
    return !arr2.some(item2 => item2 == item);
  })).concat(arr2.filter(item => {
    return !arr1.some(item2 => item2 == item);
  }));
  return newArr;
}

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

I also tried this and it also works:

function diffArray(arr1, arr2) {
  let newArr = [].concat(arr1.filter(item => {
    return !arr2.some(item2 => item2 == item);
  }));
  let newArr2 = [].concat(arr2.filter(item => {
    return !arr1.some(item2 => item2 == item);
  }));
  return newArr.concat(newArr2);
}

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

Buuuuuut... My question is... Why this last solution does not work?:

function diffArray(arr1, arr2) {
  let newArr = [].concat(arr1.filter(item => {
    return !arr2.some(item2 => item2 == item);
  }));
  newArr.concat(arr2.filter(item => {
    return !arr1.some(item2 => item2 == item);
  }));
  return newArr;
}

console.log(diffArray(
  ["andesite", "grass", "dirt", "pink wool", "dead shrub"],
  ["diorite", "andesite", "grass", "dirt", "dead shrub"]
));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 3
    The problem is that `a.concat(b)` doesn't *change* `a` - it produces new array. You have the code `newArr.concat(arr2.filter(item => { return !arr1.some(item2 => item2 == item); }));` which is the same construct. It works if you capture the new array in a variable or if you directly return it (like in the second code block). – VLAZ Nov 25 '20 at 09:42
  • Totally makes sens now, thank you ! – cyril morin Nov 25 '20 at 10:01

0 Answers0