当我对一个子数组进行排序时,如何根据已排序子数组的新顺序更改其他子数组元素的顺序:
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);
预期的数组应该是这样的:
[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 ]
最佳答案
您可以使用一个包含值对象和索引的临时数组进行排序,并将其他数组映射到已排序数组的索引。
这种方法称为 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; }
关于javascript - 如何更改多维数组中的顺序然后在 javascript 中对一个子数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795019/