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?
-
\$\begingroup\$ 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 . \$\endgroup\$Mast– Mast ♦2018年09月14日 12:40:08 +00:00Commented Sep 14, 2018 at 12:40
-
\$\begingroup\$ 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! \$\endgroup\$Edgar Ordóñez– Edgar Ordóñez2018年09月14日 12:59:50 +00:00Commented Sep 14, 2018 at 12:59
-
1\$\begingroup\$ @Bergi why not write that as an answer? Please don't use comments as a substitute for answers. Thanks \$\endgroup\$Vogel612– Vogel6122018年09月14日 13:44:10 +00:00Commented Sep 14, 2018 at 13:44
-
\$\begingroup\$ @Vogel612 Because it was off-topic on SO back when I commented :-) \$\endgroup\$Bergi– Bergi2018年09月14日 13:49:10 +00:00Commented Sep 14, 2018 at 13:49
-
\$\begingroup\$ @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. \$\endgroup\$Malachi– Malachi2018年09月14日 14:01:06 +00:00Commented Sep 14, 2018 at 14:01
1 Answer 1
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);