0

Is there a way to use a spread operator over another spread operator?

const arr = [[1,2,3],[4],[5,6],[7,8,9]];
const spreadArr = [...arr];  // This works
console.log(spreadArr); // [[1,2,3],[4],[5,6],[7,8,9]]

But, can we somehow chain it like we can over the map, filter or other methods?

With the output to probably spread the 2d-array into a 1-d one. And the code or syntax to be something like:

const doubleSpreadArr = [...(...arr)];
console.log('The expected output to be: ', doubleSpreadArr);
// The output expected to be [1,2,3,4,5,6,7,8,9]

How does the spread operator exactly work in JavaScript(v8, or any other engine)?

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • 1
    Use [`flat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)? – evolutionxbox May 25 '22 at 18:22
  • 1
    Maybe use `.flat()` method of array? – Aakash Maurya May 25 '22 at 18:24
  • 1
    Check this. https://stackoverflow.com/questions/14824283/convert-a-2d-javascript-array-to-a-1d-array – Fir3 May 25 '22 at 18:28
  • I understood the concept of flattening of multi-dimensional arrays, that can even be done using loops, but what I am trying to ask here is how does the spread operator work and what is the reason that it cannot be chained? – Trishant Pahwa May 25 '22 at 18:30
  • It's not an operator. It's part of array syntax. That's why it cannot be nested. – Bergi May 25 '22 at 19:31

0 Answers0