Concatenation vs. spread operators

Hello. I’ve read a couple of Stack Overflow discussions on this, but still am not clear on when it is best to use concatenation vs. the spread operator. For example, can you explain why this code works?..

function diffArr(arr1, arr2){
  return arr1.concat(arr2).filter(c => !arr1.includes(c) || !arr2.includes(c));
}

But why this code does not work,?

function diffArr(arr1, arr2){
  return [...arguments].filter(c => !arr1.includes(c) || !arr2.includes(c));
}

I wrote the script below to compare the outputs of concat vs. spread …, and they look identical to me.

function testFoo(arr1,arr2){
    var fooCat = arr1.concat(arr2);
    var fooArg = [...arguments];
    var fooGoo = [...arr1,arr2];
    return fooCat + " "+fooArg+" "+fooGoo;
}
undefined
testFoo(['a','b','c'],["@","#","!"])

“a,b,c,@,#,! a,b,c,@,#,! a,b,c,@,#,!”```

If your function arguments are arrays, using the spread operator on the arguments object will not give you one-dimensional array. Instead you’ll get an array of two arrays, like so: [[1, 2, 3], [1, 2, 4]]. So when you go to use the filter method on it, the ‘c’ represents the inner array.

In contrast, in the first example, concatenating first array argument onto second gives you a one-dimensional array. Using filter method on that goes through each number.

1 Like
function diffArr(arr1, arr2){
  // all elements 1 big array, if element is absent in either array put in result
  return arr1.concat(arr2).filter(c => !arr1.includes(c) || !arr2.includes(c));
}

function diffArr2(arr1, arr2){
 //console.log ([...arguments]) //see why here
 // array of two subarray elements, neither of which is element on arr1 or arr2 
  return [...arguments].filter(c => !arr1.includes(c) || !arr2.includes(c));
}
1 Like

Oh wow, really good to know about spread operators ‘nesting’ arrays a level deeper. Thank you !

Excellent, thank you. I understand it clearly now.:smiley:

You’re welcome. Always glad to help someone who is willing to dissect one of the challenges even after they have a working solution in hand.

Glad I could help :slight_smile: