0

I have a multidimensional array which can contain a different number of arrays. What I want to do is to match all arrays in order of key not value, and produce a new array for each row created, something like this

var arr = [
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5]
]

The result I need

var arr = [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4],[5,5,5,5]]

how can I achieve this?

Hans
  • 29
  • 3

2 Answers2

1

I think here is what you are looking for.

var arr = [
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5]
];

var res = arr.reduce((x, y) => {
  for(let i in y) {
    x[i] ? x[i].push(y[i]) : x[i] = [y[i]];
  }
  
  return x;
}, []);

console.log(res);
Shubham
  • 1,755
  • 3
  • 17
  • 33
0

I hope that you are looking for this one. It retrieves column and row lengths implicitly within the map(). Source [Swap rows with columns (transposition) of a matrix in javascript

function transpose(a) {
    return Object.keys(a[0]).map(function(c) {
        return a.map(function(r) { return r[c]; });
    });
}
      


        console.log(transpose([
            [1,2,3,4,5],
      [1,2,3,4,5],
      [1,2,3,4,5],
      [1,2,3,4,5]
        ]));
Sai Manoj
  • 3,809
  • 1
  • 14
  • 35