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
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
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);
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())
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)
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);