由于代码写得不好。我必须对一个数组进行排序,并基于该排序,以相同的顺序对另一个数组进行排序。例如:
foo =[ ['tom', 20, {teacher: 'may', class: 'math'}],
['Ann', 21, {teacher: 'Joe', class: 'CS'}],
['tony', 22, {teacher: 'may', class: 'math'}]
]
bar = [{extraPara: 'ran1', Sequence 2},
{extraPara: 'ran2', Sequence 1},
{extraPara: 'ran3', Sequence 3},
]
我想用序列对栏进行排序。我也想根据该序列对 foo 进行排序。基本上两个数组应该在一个大数组中,但是由于编码错误,它被分开了。但是我没有时间重新编写整个结构。
最有效的方法是什么?
我可以轻松地按以下方式对栏进行排序:
bar = _.sortBy(bar, function(item) {return item.Sequence})
我知道如何做到这一点的唯一方法是自己编写排序算法,每当我更改 bar 的顺序时,我都会使用索引并对 foo 执行相同的操作。然而,这听起来效率很低,可读性也很差
有什么建议吗?
最佳答案
您可以使用带有索引的辅助数组,并按顺序对它们进行排序,并将带有排序索引的 foo 数组映射为新的排序数组。
var foo = [['tom', 20, { teacher: 'may', class: 'math' }], ['Ann', 21, { teacher: 'Joe', class: 'CS' }], ['tony', 22, { teacher: 'may', class: 'math' }]],
bar = [{ extraPara: 'ran1', Sequence: 2 }, { extraPara: 'ran2', Sequence: 1 }, { extraPara: 'ran3', Sequence: 3 }],
order = bar.map(function (_, i) {
return i;
}).sort(function (a, b) {
return bar[a].Sequence - bar[b].Sequence;
}),
result = order.map(function (i) {
return foo[i];
});
console.log(order);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 将一个数组与另一个数组排序最有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44833894/