3 回答
TA贡献1807条经验 获得超9个赞
首先设置自定义优先级
var codePriority = [ "GREEN", "BLUE", "RED" ];
现在使用相同的排序方式
arr.sort( function(a,b){
if ( a.code == b.code ) return a.value - b.value;
return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) ; notice this line
})
演示版
var arr = [
{ code: "RED", value: 0},
{ code: "BLUE", value: 0},
{ code: "RED", value: 0},
{ code: "GREEN", value: 0},
{ code: "BLUE", value: 0},
{ code: "RED", value: 0},
{ code: "GREEN", value: 0},
{ code: "BLUE", value: 0}
];
var codePriority = [ "GREEN", "BLUE", "RED" ];
arr.sort( function(a,b){
if ( a.code == b.code ) return a.value - b.value;
return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code )
});
console.log( arr );
TA贡献1811条经验 获得超4个赞
您可以实现一个模式数组,并根据该模式数组中元素的索引进行排序。
const a = ['GREEN', 'BLUE', 'RED'];
const o = [{code:"RED",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0}];
const r = o.slice().sort(({ code: q }, { code: w }) => a.indexOf(q) - a.indexOf(w));
console.log(r);
添加回答
举报