0

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?

Alex Wang
  • 411
  • 3
  • 12
  • 1
    Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Daniel Brose May 07 '20 at 05:25
  • Use `array.flatMap(x => x.map(y => y*2))` or `array.map(x => x.map(y => y*2)).flat()` – adiga May 07 '20 at 05:43

4 Answers4

2

const array = [
  [1, 2],
  [3, 4]
];
const result = array.reduce((elem, accum) => accum.concat([...elem]), []);
console.log(result);
Karan
  • 11,176
  • 3
  • 24
  • 37
Arun Mohan
  • 1,177
  • 1
  • 4
  • 11
1

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);
Hien Nguyen
  • 23,011
  • 7
  • 48
  • 55
1

you can try this:

array.flat(Infinity)

// [1, [2, [3]]].flat(Infinity) =>  [1, 2, 3]
super wang
  • 162
  • 6
0

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 ]
Mulan
  • 119,326
  • 28
  • 214
  • 246