I have a nested array
const array = [[1, 2], [3, 4]];
I want to return a single array like [2,4,6,8]
.
I did this:
const result = array.map((x)=>{
return x.map((y)=>y*2)
});
But it returned [[2,4],[6,8]]
.
What should I do?
I have a nested array
const array = [[1, 2], [3, 4]];
I want to return a single array like [2,4,6,8]
.
I did this:
const result = array.map((x)=>{
return x.map((y)=>y*2)
});
But it returned [[2,4],[6,8]]
.
What should I do?
const array = [
[1, 2],
[3, 4]
];
const result = array.reduce((elem, accum) => accum.concat([...elem]), []);
console.log(result);
You can convert 2D array to 1D array use
result = [].concat(...result);
const array = [[1, 2], [3, 4]];
var result = array.map((x)=>{
return x.map((y)=>y*2)
});
result = [].concat(...result);
console.log(result);
You are simply looking for Array.prototype.flatMap
-
const array =
[[1, 2], [3, 4]]
const result =
array.flatMap(a => a.map(x => x * 2))
console.log(result)
// [ 2, 4, 6, 8 ]