How is ...rest applied to a function?

Tell us what’s happening:
I am doing some revision and taking the time to understand alternate answers to this challenge.

I am failing to understand how ...rest is being used in the code below.

May you please explain in layman term, what is happening in the first return and why it is important to structure the code as demonstrated below?

I suspect that it is a way of concatenating the two arrays.

  **Your code so far**

function diffArray(arr1, arr2) {
  return [...diff(arr1, arr2), ...diff(arr2, arr1)];

  function diff(a, b) {
    return a.filter(item => b.indexOf(item) === -1);
  }
}

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/99.0.4844.51 Safari/537.36

Challenge: Diff Two Arrays

Link to the challenge:

this is not rest, this is spread

diff returns an array, it’s the same as

const a = [1,2,3];
const b = [4, 5, 6];

const c = [...a, ...b];

c is a monodimensional array because a and b are spread into their elements

1 Like

diff(arr1, arr2) and diff(arr2, arr1) both return arrays.
That means that return [diff(arr1, arr2), diff(arr2, arr1)]; would return a 2-dimensional array: [ [], [4] ].
We want to return a single array: [4]

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.