Search code examples
javascriptarraysjavascript-objects

Turn matrix into column-wise new flat array


I'm working with an array of arrays, and each inner array contains objects.

I would like to reorganise this array to a flat array, where the order is column-wise (see below).

Currently I have written this:

const newArray = [];

arr.map((rows, i) => {
  rows.map((row) => {
     newArray.splice(i, 0, row);
    });
  });

But the order starts going wrong further into the operation.

(For note I'm using a Promise library inside of Node so treat the maps as normal maps)

Current Array

const arr = [
  [
    { Mapped_Index: 'Alignment', item_1: '-' },
    { Mapped_Index: 'Alignment', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Alignment', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Alignment', item_6: '-', item_7: '-' }
  ],
  [
    { Mapped_Index: 'Autonomy', item_1: '-' },
    { Mapped_Index: 'Autonomy', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Autonomy', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Autonomy', item_6: '-', item_7: '-' }
  ],
  [
    { Mapped_Index: 'Belonging', item_1: '-' },
    { Mapped_Index: 'Belonging', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Belonging', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Belonging', item_6: '-', item_7: '-' }
  ]
]

Expected Array

const arr = [
    { Mapped_Index: 'Alignment', item_1: '-' },
    { Mapped_Index: 'Autonomy', item_1: '-' },
    { Mapped_Index: 'Belonging', item_1: '-' },
   
    { Mapped_Index: 'Alignment', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Autonomy', item_2: '-', item_3: '-' },
    { Mapped_Index: 'Belonging', item_2: '-', item_3: '-' },
   
    { Mapped_Index: 'Alignment', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Autonomy', item_4: '-', item_5: '-' },
    { Mapped_Index: 'Belonging', item_4: '-', item_5: '-' },
  
    { Mapped_Index: 'Alignment', item_6: '-', item_7: '-' },
    { Mapped_Index: 'Autonomy', item_6: '-', item_7: '-' },
    { Mapped_Index: 'Belonging', item_6: '-', item_7: '-' }
]

Solution

  • It looks like you want to transpose the original matrix, and then flatten that:

    let result = arr[0].flatMap((_, i) => arr.map(row => row[i]));