有几种方法:
使用indexOf重复搜索labels数组
使用地图查找标签的索引更快
这是一个使用 indexOf 的示例(在 ES2015+ 中):
arrayToBeSorted.sort((a, b) => labels.indexOf(a.label) - labels.indexOf(b.label));
实时复制:
var arrayToBeSorted = [{label: 'firstLabel', value: 123}, {label: 'secondLabel', value: 456}, {label: 'thirdLabel', value: 789}];
var labels = ['secondLabel', 'thirdLabel', 'fourthLabel', 'firstLabel'];
arrayToBeSorted.sort((a, b) => labels.indexOf(a.label) - labels.indexOf(b.label));
console.log(arrayToBeSorted);
请注意,如果labels 中不存在标签,indexOf 将返回-1,这将使未知标签出现在结果的开头。如果您希望它们放在最后,请检查 -1 并将其替换为 Infinity。
这是一个使用地图来加快查找这些索引的示例(在 ES2015+ 中):
const map = new Map(labels.map((label, index) => [label, index]));
arrayToBeSorted.sort((a, b) => {
let aindex = map.get(a.label);
if (aindex === null) {
aindex = -1; // Or Infinity if you want them at the end
}
let bindex = map.get(b.label);
if (bindex === null) {
bindex = -1; // ""
}
return aindex - bindex;
});
实时复制:
var arrayToBeSorted = [{label: 'firstLabel', value: 123}, {label: 'secondLabel', value: 456}, {label: 'thirdLabel', value: 789}];
var labels = ['secondLabel', 'thirdLabel', 'fourthLabel', 'firstLabel'];
const map = new Map(labels.map((label, index) => [label, index]));
arrayToBeSorted.sort((a, b) => {
let aindex = map.get(a.label);
if (aindex === null) {
aindex = -1; // Or Infinity if you want them at the end
}
let bindex = map.get(b.label);
if (bindex === null) {
bindex = -1; // ""
}
return aindex - bindex;
});
console.log(arrayToBeSorted);
这是为了清楚起见并避免在回调中多次查找标签。以地图中的第二个标签查找为代价可以更简洁:
const map = new Map(labels.map((label, index) => [label, index]));
arrayToBeSorted.sort((a, b) => {
const aindex = map.has(a.label) ? map.get(a.label) : -1; // Or Infinity if you want them at the end
const bindex = map.has(b.label) ? map.get(b.label) : -1; // "
return aindex - bindex;
});
实时复制:
var arrayToBeSorted = [{label: 'firstLabel', value: 123}, {label: 'secondLabel', value: 456}, {label: 'thirdLabel', value: 789}];
var labels = ['secondLabel', 'thirdLabel', 'fourthLabel', 'firstLabel'];
const map = new Map(labels.map((label, index) => [label, index]));
arrayToBeSorted.sort((a, b) => {
const aindex = map.has(a.label) ? map.get(a.label) : -1; // Or Infinity if you want them at the end
const bindex = map.has(b.label) ? map.get(b.label) : -1; // "
return aindex - bindex;
});
console.log(arrayToBeSorted);
甚至可以是:
const map = new Map(labels.map((label, index) => [label, index]));
arrayToBeSorted.sort((a, b) =>
(map.has(a.label) ? map.get(a.label) : -1) - (map.has(b.label) ? map.get(b.label) : -1)
);
...但是对我来说,调试等时让生活变得太困难了。