0

Say I have an array with arrays inside it. I would like to flatten it and get a single array with all the values.

let arrWithArrs = [[1,2,3], [4,5,6]];
let array = arrWithArrs.map(arr => ...arr);

This obviously doesn't work but I would like to know how to make it work. The wanted outcome would be

array = [1,2,3,4,5,6];
VLAZ
  • 18,437
  • 8
  • 35
  • 54
Valchy
  • 71
  • 3
  • 11
  • 2
    [Array.prototype.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) - ES2019 – ASDFGerte Oct 17 '19 at 13:55
  • 1
    `let array = arrWithArrs.flat()`, just to exemplify ASDFGerte's documentation link. – Patrick Roberts Oct 17 '19 at 13:56
  • What you describe is *not* [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). It's flattening arrays to remove other inner arrays. Destructuring assignments will take values out of arrays and specifically assign those to variables. – VLAZ Oct 17 '19 at 13:57

1 Answers1

0

You can perform a reduce on the array to combine each of the arrays into a single array like so: arrWithArrs.reduce((result, lst) => [...result, ...lst], []);

labennett
  • 187
  • 5