Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Đinh Carabus Avatar asked Dec 06 '16 08:12

Đinh Carabus


2 Answers

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; }
like image 129
Nina Scholz Avatar answered Oct 02 '22 13:10

Nina Scholz


You could do something like this.

var order = myRows[0].map(function(e) { return e.idx })
myRows.forEach(function(row) { 
    row.sort(function(a,b) { 
        return order.indexOf(a.idx) - order.indexOf(b.idx);
    });
});

This is very simple code just to demonstate the idea. It will probably be slow for very large arrays.

like image 35
gnud Avatar answered Oct 02 '22 12:10

gnud