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
  • 16
  • 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
  • 12,059
  • 3
  • 24
  • 40
Arun Mohan
  • 1,207
  • 1
  • 5
  • 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
  • 24,551
  • 7
  • 52
  • 62
1

you can try this:

array.flat(Infinity)

// [1, [2, [3]]].flat(Infinity) =>  [1, 2, 3]
XuWang
  • 179
  • 7
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
  • 129,518
  • 31
  • 228
  • 259