How can I sort all columns of a matrix in javascript?
I'm trying to solve this exercise but I could use some help. I want to sort all the columns of this matrix in an ascending order but this code only sorts the first one. Any idea what should I do?
<script>
var matrix = [
[ 0, 8, 1, 1, 10, 6 ],
[ 6, 8, 7, 0, 3, 9],
[ 0, 7, 6, 8, 6, 5],
[ 4, 0, 2, 7, 2, 0],
[ 4, 4, 5, 7, 5, 1]
];
var colSort = matrix.sort(function(a,b) {
return a[0]b[0]
});
console.log(colSort);
// sums of one specific row
var rowSum = matrix[3].reduce((a, b) => a + b);
// sums of columns
var colSum = matrix.reduce((a, b) => a.map((x, i) => x + b[i]));
console.log(rowSum);
console.log(colSum);
</script>
This should be output after sort:
[[0, 0, 1, 0, 2, 0],
[0, 4, 2, 1, 3, 1],
[4, 7, 5, 7, 5, 5],
[4, 8, 6, 7, 6, 6],
[6, 8, 7, 8, 10, 9]]
3 answers

What you should do is flip the matrix so that all the rows are columns and all the columns are rows, using this
zip
function:var zip = rows => rows[0].map((_,c) => rows.map(row=>row[c])); var flipped = zip(matrix);
Then you can sort each row:
for (var i = 0; i < flipped.length; i++) { flipped[i] = flipped[i].sort((a, b) => a  b); }
Then flip it back:
var finalUnflippedResult = zip(flipped);
Putting it all together you get:
var zip = rows => rows[0].map((_,c) => rows.map(row=>row[c])); var flipped = zip(matrix); for (var i = 0; i < flipped.length; i++) { flipped[i] = flipped[i].sort((a, b) => a  b); } var result = zip(flipped);

Or you can do this as mention in comment.
var matrix = [ [ 0, 8, 1, 1, 10, 6 ], [ 6, 8, 7, 0, 3, 9], [ 0, 7, 6, 8, 6, 5], [ 4, 0, 2, 7, 2, 0], [ 4, 4, 5, 7, 5, 1] ]; matrix=matrix.map((col, i) => matrix.map(row => row[i]));//take transpose of matrix matrix.forEach(function(e){ //sort the rows of martix e.sort() }); console.log(matrix.map((col, i) => matrix.map(row => row[i]))); //transpose it again

var matrix = [ [0, 8, 1, 1, 10, 6], [6, 8, 7, 0, 3, 9], [0, 7, 6, 8, 6, 5], [4, 0, 2, 7, 2, 0], [4, 4, 5, 7, 5, 1] ]; console.log(matrix); var colsArr = []; function takeColumn(arr, colNum) { var resultColumn = []; for (let i = 0; i < arr.length; i++) { resultColumn.push(matrix[i][colNum]); } return resultColumn.sort(function (a, b) { return a  b; }); }; for (let r = 0; r < 6; r++) { colsArr.push(takeColumn(matrix, r)); } console.log(colsArr); transpose = arr => arr[0].map((x, i) =>arr.map(x => x[i])); console.log(transpose(colsArr));