0

Here is my multi-dimensional array:

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

I'm 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 was unable to achieve the desired result.

Looking for help here.

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.