I did this Codepen to combine all the columns from one matrix in JS.

const matrix = [
  ['a', 'a', 'a'],
  ['b', 'b', 'b'],
  ['c', 'c', 'c']
];

const combineMatrixColumns = (matrix) => {
  const biggest = matrix.reduce((acc, arr) => acc.length < arr.length ? arr : acc, []);

  return biggest.reduce((acc, item, index) => {
    matrix.forEach(item => item[index] ? acc = [...acc, item[index]] : null)
    return acc;
  }, [])
};

const result = combineMatrixColumns(matrix)
console.log(result)

For this input, the expected output as a single array with each column combined:

["a", "b", "c", "a", "b", "c", "a", "b", "c"]

My question is: You know a better approach to do it?

migrated from stackoverflow.com Sep 4 at 23:37

This question came from our site for professional and enthusiast programmers.

  • Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. – Mast Sep 14 at 12:40
  • Hi @Mast, Sorry for that, I'm new, and I need to read more the docs as can I see. I put here the changes that I did. codepen.io/edgarordonez/pen/dqRWLg I'm doing that for merge the responses from different API's and show them combined in the interface. I'm not sure if it replies to your question. Thanks! – Edgar Ordóñez Sep 14 at 12:59
  • 1
    @Bergi why not write that as an answer? Please don't use comments as a substitute for answers. Thanks – Vogel612 Sep 14 at 13:44
  • @Vogel612 Because it was off-topic on SO back when I commented :-) – Bergi Sep 14 at 13:49
  • @Bergi, please feel free to post a review of the code, now that the post has been placed on a site where that sort of thing belongs in an answer instead of a comment. – Malachi Sep 14 at 14:01

You can simply use two nested for loops for this, which makes it implementation much more simpler.Plus this helps you to avoid creating a map or performing concatenation operations. The below code is based on the logic of transposing the matrix.

const matrix = [ ['a', 'a', 'a'], ['b', 'b', 'b'], ['c', 'c', 'c'] ];
var result = [];

for(let i = 0; i < matrix[0].length; i++){
  for(let j = 0; j < matrix[0].length; j++){
    result.push(matrix[j][i]);
  }
}
 console.log(result);

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.