我正在尝试根据第二个数组中的排序顺序对JavaScript数组进行排序。我已经在SO中遇到了其他类似的问题,并提出了以下代码。输出没有达到预期的效果。
var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];
legends.sort( function (a, b) {
return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];
});
console.log(legends);
所需的输出是
["Chemistry", "Maths", "French", "English", "Physics"];
我试图在纯JS或使用D3js中获得所需的输出,不确定我是否做得对!
答案 0 :(得分:3)
你几乎是正确的但是在sort函数中,你引用了正在变异的#include <vector>
数组,因此索引与原始顺序不匹配。
为了证明这种情况,您可以复制数组并对副本进行排序:
legends
答案 1 :(得分:3)
你可以带一个带索引的辅助数组,对它们进行排序并映射想要的数组。
var legends = ["Maths", "Physics", "English", "French", "Chemistry"],
sortOrder = [1, 400, 300, 200, -3];
legends = [...legends.keys()]
.sort((a, b) => sortOrder[a] - sortOrder[b])
.map(i => legends[i]);
console.log(legends);
&#13;
答案 2 :(得分:1)
尝试以下
var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];
/* Create an array of objects of value index of sortOrder */
legends = Object.entries(sortOrder.reduce((a,v,i) => Object.assign(a, {[v]:i}), {}))
.sort((a,b) => a[0] - b[0]) // Sort array based on sortOrder values
.map(([s, i]) => legends[i]); // fetch items from legends based on sorted order
console.log(legends);
&#13;