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?

5
  • Do you mean convert rows into columns and columns into rows? Commented Feb 28, 2018 at 4:31
  • through the use of code ... have at it then come back when you're stuck :p Commented Feb 28, 2018 at 4:31
  • const rotate = a => Object.keys(a[0]).map(c => a.map(r => r[c] )); - oh, wait, you don't want to rotate the array, you just want an array of arrays of the same value? Commented Feb 28, 2018 at 4:36
  • your sample input and output are actually ambiguous ... what if the input is [[1,2,3],[4,5,6],[7,8,9]] what output would you expect? Commented Feb 28, 2018 at 4:49
  • Or better yet const fn=a=>a[0].map((c, i)=>a.map(r=>r[i])); Commented Feb 28, 2018 at 4:57

2 Answers 2

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);

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

3 Comments

nevermind my comment :p
@JaromandaX He wants in order of keys not values. His query was "I want to do is to match all arrays in order of key not value"
I misread your code :p
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]
        ]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.