0

I have an array of arrays like this

[
 [2, 0, 0, 2, 0],
 [4, 0, 0, 0, 1],
 [1, 1, 0, 0, 0],
 [1, 0, 1, 0, 0]
]

And I am trying to create a new array by getting the first value of each array so the output will be

[
 [2, 4, 1, 1],
 [0, 0, 1, 0],
 [0, 0, 0, 1],
 [2, 0, 0, 0],
 [0, 1, 0, 0]
]

Is there any workarounds to achieve it? Thanks

Kaung Khant Zaw
  • 1,508
  • 3
  • 19
  • 31

1 Answers1

1

Looping based on the subarray length, using Array.prototype.flatMap, you can get the array of the ith item of child array as a new array.

const input = [
  [2, 0, 0, 2, 0],
  [4, 0, 0, 0, 1],
  [1, 1, 0, 0, 0],
  [1, 0, 1, 0, 0]
];

const output = [];
for (let i = 0; i < input[0].length; i ++) {
  output.push(input.flatMap(item => item[i]));
}

console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39