JavaScript如何基于指定值数组对对象数组进行自定义排序
最优实现方案
优先用哈希表存储选中项的优先级,避免排序过程中重复查找选中数组,性能最优:
const list = [ { name: 'BMW' }, { name: 'AUDI' }, { name: 'MINI' }, { name: 'FIAT' }, { name: 'KIA' }, ] const selected = [ 'MINI', 'KIA' ] // 构建优先级映射,仅需遍历一次selected数组 const priorityMap = new Map(selected.map((name, index) => [name, index])) list.sort((a, b) => { const aHas = priorityMap.has(a.name) const bHas = priorityMap.has(b.name) // 都在选中列表内:按selected中的顺序排序 if (aHas && bHas) { return priorityMap.get(a.name) - priorityMap.get(b.name) } // 仅a在选中列表:a排前面 if (aHas) return -1 // 仅b在选中列表:b排前面 if (bHas) return 1 // 都不在选中列表:可自定义规则,返回0则保持原数组的相对顺序,也可以按名称字母排序 return 0 // 如果需要不在选中列表的项按字母升序排列,替换上面的return 0为: // return a.name.localeCompare(b.name) })
运行后list就是你需要的预期结果。
简化写法(仅适用于selected数组很短的场景)
如果你的selected数组长度很小,也可以用更短的写法,缺点是每次排序比较都要遍历一次selected数组,性能比哈希表方案差:
list.sort((a, b) => { const aIdx = selected.indexOf(a.name) const bIdx = selected.indexOf(b.name) if (aIdx > -1 && bIdx > -1) return aIdx - bIdx if (aIdx > -1) return -1 if (bIdx > -1) return 1 return 0 })
注意事项
Array.sort是原地排序,会直接修改原数组,如果需要保留原数组不变,可以先浅拷贝再排序:
const sortedList = [...list].sort(/* 上面的排序逻辑 */)
内容的提问来源于stack exchange,提问作者Martyn Ball
相关产品推荐
相关产品推荐

