Home > Software design >  Elegant way to REDUCE a 2D array into 1D
Elegant way to REDUCE a 2D array into 1D

Time:01-12

Given the following 2D array: var arr = [[1,2,3],[4,5,6],[7,8,9]]

How can get [1,4,7] without using for loops?

My simplest solution is transposing and returning only the first (0th) row. There must be a more elegant solution, Perhaps something that I can chain onto an array to make it a one-liner?

CodePudding user response:

Try doing

var arr = [[1,2,3],[4,5,6],[7,8,9]];
var newaArr = arr.map(el => el[0]);
  •  Tags:  
  • Related