When I sort one subarray how can I change the order of other subarray's elements according to the new order of sorted subarray:
var op = [];
op[0] = [0, "1:7001", "1:7002", "1:7003", "1:7004", "1:7005"];
op[1] = [1, "1:8001", "1:8002", "1:8003", "1:8004", "1:7005"];
op[2] = ["asw", 3, 5, 1, 10, 2];
op[2] = op[2].slice(0, 1).concat(op[2].slice(1, op[2].length).sort(function(a,b) {
return b - a;
}));
console.log(op);
The expected array should look like:
[0, "1:7004", "1:7002", "1:7001", "1:7005", "1:7003"];
[1, "1:8004", "1:8002", "1:8001", "1:7005", "1:8003"];
[ "asw", 10, 5, 3, 2, 1 ]
You could take a temporary array with objects of value and index for sorting and map the other arrays with the indices of the sorted array.
This approach is called sorting with map.
var op = [
[0, "1:7001", "1:7002", "1:7003", "1:7004", "1:7005"],
[1, "1:8001", "1:8002", "1:8003", "1:8004", "1:7005"],
["asw", 3, 5, 1, 10, 2]
],
order = op[2] // take op[2] as pattern
.slice(1) // omit first element
.map((v, i) => ({ v, i: i + 1 })) // take value and index with offset
.sort(({ v: a }, { v: b }) => b - a); // sort by value desc
order.unshift({ i: 0 }); // keep first item at index zero
op = op.map(a => order.map(({ i }) => a[i])); // map value at index
console.log(op);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With