Diff Two Arrays - improvement

Diff Two Arrays - improvement
0

#1

Tell us what’s happening:
This code works, but I would like to improve it and make simpler. Does anyone have better solutions?

Your code so far


function diffArray(arr1, arr2) {
  var newArr = arr1.filter(a => !arr2.includes(a));
  var newestArr = arr2.filter(b => !arr1.includes(b));
  return newArr.concat(newestArr);
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

Take a look at other solutions by clicking the Get a Hint button located on the challenge. Also, what do you define as a better solution?


#3

Thanks for the blur:)
I feel like my solution is too long, has too many steps. I guess what I mean is whether I can make it shorter? More efficient? Easier to read?


#4

About the only way of making it shorter, but would not change the speed, would be to create a function which accepts two arrays. The function would basically be a more generic way of using the filter method you have written. I won’t show you how to write the function itself, but I will show the general structure of the diffArray function:

function diffArray(arr1, arr2) {
  const diff = (one, two) => /*  generic version of your use of filter method goes here */
  return diff(arr1, arr2).concat(diff(arr2,arr1));
}

OR

function diffArray(arr1, arr2) {
  const diff = (one, two) => /*  generic version of your use of filter method goes here */
  return [...diff(arr1, arr2), ...diff(arr2,arr1)];
}