在javascript中对一个子数组进行排序时,如何更改多维数组的顺序?

时间:2018-12-15 16:22:41

标签: javascript arrays

当我对一个子数组排序时,如何根据新的排序子数组顺序更改其他子数组元素的顺序:

<input type="text" id="input" placeholder="your new password" disabled>

预期的数组应类似于:

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

1 个答案:

答案 0 :(得分:3)

您可以使用带有值和索引对象的临时数组进行排序,并使用已排序数组的索引映射其他数组。

这种方法称为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; }