-1

I have this array

[[1,2,3][4,5,6][7,8,9]]

how to get from this such

[1,2,3,4,5,6,7,8,9]

without using Array.map

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    [`Array.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – Sirko May 07 '19 at 04:45

5 Answers5

1

You can do:

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const result = data.reduce((a, c) => a.concat(c), []);

console.log(result);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

use Array#flatMap method to flatten returned arrays.

let data = [
  [1, 2, 3],[4, 5, 6],[7, 8, 9]
];


console.log(data.flatMap(a => a))

Or use Array#reduce method to iterate and reduce into a single array.

let data = [
  [1, 2, 3],[4, 5, 6],[7, 8, 9]
];


console.log(data.reduce((arr, a) => [...arr, ...a]), [])

Or even you can use the built-in Array#flat method which is created for this purpose. If you want to fatten a nested array then specify the depth argument by default it would be 1.

let data = [
  [1, 2, 3],[4, 5, 6],[7, 8, 9]
];


console.log(data.flat())
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You can use array flat

let k = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

let m = k.flat();
console.log(m)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can use flat()

const arr = [[1,2,3],[4,5,6],[7,8,9]]
console.log(arr.flat())

If you don't want to use flat() then you can use push() and spread operator.

const arr = [[1,2,3],[4,5,6],[7,8,9]]
const res = [];
arr.forEach(x => res.push(...x))
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use Array​.prototype​.flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

var arr = [[1,2,3],[4,5,6],[7,8,9]];
var res = arr.flat();
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59