Below the Radar
Below the Radar

Reputation: 7635

Sort columns in a matrix

I have a matrix (or a multidimensional array) of non unique values like this one:

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.

//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

I would prefer a lodash solution if possible.

Upvotes: 0

Views: 223

Answers (2)

trincot
trincot

Reputation: 350715

Using lodash you could transpose the matrix with zip, sort it with sortBy by a given row number, and then transpose it back:

_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

With the rest parameter syntax you can also write this as:

_.zip(..._.sortBy(_.zip(...matrix), row));

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386670

You could use an array with the indices and sort it with the values of matrix[0]. Then build a new array with sorted elements.

var matrix = [[1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 6

Related Questions