Search code examples
javascriptsortingmatrixlodash

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.


Solution

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