Home > Net >  Extract the first element from nested array into new array angular
Extract the first element from nested array into new array angular

Time:01-07

Here is my array

newItem = [['ID', ['item 1A','item 1B','item 1C']], ['Address',[item 2A','item 2B','item 2C']], ['Req',['item 3A', 'item 3B', 'item 3C']]]

Im trying to extract it into a new array in the below format

newArr = [['item 1A', 'item 2A', 'item 3A'], ['item 1B', 'item 2B', 'item 3B'], ['item 1C', 'item 2C', 'item 3C']]

Tried several ways with map, flat etc but unable to achieve the desired result.

Looking for help here

Cheers, Sheetal

CodePudding user response:

What you want is transposing the matrix, and you can simply use map to achieve this:

const newItem = [
  ['ID', ['item 1A', 'item 1B', 'item 1C']],
  ['Address', ['item 2A', 'item 2B', 'item 2C']],
  ['Req', ['item 3A', 'item 3B', 'item 3C']]
]

const matrix = newItem.map(item => item[1]) // turn the array into matrix

const newArr = matrix[0].map((_, i) => matrix.map(item => item[i])) // transpose the matrix

console.log(newArr)

  • Related