javascriptarrayssortingrowsorter

Sort other arrays by order of specific array?


I have a bunch of arrays in this form:

var myRows = [
    [{idx: 0, val: 90}, {idx: 1, val: 75}, {idx: 2, val: 35}],
    [{idx: 0, val: 50}, {idx: 1, val: 17}, {idx: 2, val: 95}],
    [{idx: 0, val: 10}, {idx: 1, val: 24}, {idx: 2, val: 80}]
  // ...
];

Lets say I would like to sort the first row ascending by val, so it becomes:

[{idx: 2, val: 35}, {idx: 1, val: 75}, {idx: 0, val: 90}]

Is there an easy way to sort the remaining arrays, so that their order matches the idx-order of the sorted first row?

myArrays = [
    [{idx: 2, val: 35}, {idx: 1, val: 75}, {idx: 0, val: 90}]
  , [{idx: 2, val: 95}, {idx: 1, val: 17}, {idx: 0, val: 50}]
  , [{idx: 2, val: 80}, {idx: 1, val: 24}, {idx: 0, val: 10}]
  // ...
];

Maybe this is even possible without the idx property?


Solution

  • You could use sorting with map and apply the mapping for all items.

    This proposal saves the indices, order the array and applies the order to all other arrays as well.

    // the array to be sorted
    var list = [[{ idx: 0, val: 90 }, { idx: 1, val: 75 }, { idx: 2, val: 35 }], [{ idx: 0, val: 50 }, { idx: 1, val: 17 }, { idx: 2, val: 95 }], [{ idx: 0, val: 10 }, { idx: 1, val: 24 }, { idx: 2, val: 80 }]];
    
    // temporary array holds objects with position and sort-value
    var mapped = list[0].map(function (el, i) {
        return { index: i, value: el.val };
    })
    
    // sorting the mapped array containing the reduced values
    mapped.sort(function (a, b) {
        return a.value - b.value;
    });
    
    // rearrange all items in list
    list.forEach(function (a, i, aa) {
        aa[i] = mapped.map(function (el) {
            return a[el.index];
        });
    });
    
    console.log(list);
    .as-console-wrapper { max-height: 100% !important; top: 0; }