Concatenation vs. spread operators

Concatenation vs. spread operators
0

#1

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,@,#,!”```


#2

While the above three variables all are arrays, the return statement creates a string because of the concatenation operator.

return fooCat + " "+fooArg+" "+fooGoo;

#3

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


#4

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.


#5
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));
}

#6

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


#7

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


#8

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.


#9

Glad I could help :slight_smile: