需求场景:
var list = [
{recordType:"7,1"},
{recordType:"5,6"},
{recordType:"3"},
{recordType:"8"},
{recordType:"2"},
]
var sortOrder = ["3","1","5","2","7","8","9","10","6"];
将list的recordType根据sortOrder所示的顺序对list进行排序;
实现方法:
list.sort(function(a, b) {//a,b代表数组中的两个元素
//找到recordType中包含的数字在sortOrder数组中的索引位置,如果没有满足条件的元素,则返回-1
var aIndex = sortOrder.findIndex(function(value) {
return a.recordType.includes(value);
});
var bIndex = sortOrder.findIndex(function(value) {
return b.recordType.includes(value);
});
console.log(a,b,aIndex,bIndex)
//比较a和b的索引位置(即aIndex和bIndex),确定他们在sortOrder数组中的先后顺序,如果a的索引小于b的索引,则a排在b的前面,反之排在b的后面,索引相同则相对顺序不变
return aIndex - bIndex;
});
chrome调试的日志打印结果: