-1

I have some large data objects that come back to me in record formats, as an array of arrays. Column headings are in the array at index 0, and Row headings are in index 0 of each array. Sometimes, it will be necessary to translate (pivot) all of the records so that rows become columns and columns become rows.

For example:

const what_i_have = [
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3],
    [4,4,4,4]
]

const what_i_need = [
    [1,2,3,4],
    [1,2,3,4],
    [1,2,3,4],
    [1,2,3,4]
]
aidangarza
  • 251
  • 2
  • 12

1 Answers1

1

The simplest way to do this, if you know that every child array has the same length, is to create an empty array with the length of the input array's children. Then you can just map over it and use the index in the map to fill it with values from the original array.

function pivot (table) {
  return Array(table[0].length).fill() // Create array with desired length
    .map((row, i) => // Map over the new rows
      table.map(col => col[i]) // Fill them by mapping over old rows
    )
}
aidangarza
  • 251
  • 2
  • 12