A Better Solution? - Diff Two Arrays

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 :thinking: 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.

Ignore the above… Just stumbled upon this post…


1 Like

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)

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]);

Great, simple solution man!

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


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