JavaScript中如何依据指定字符串数组对目标字符串数组高效排序
实现方案
核心思路是先将指定顺序的参考数组转换为「值-优先级索引」的映射表,排序时直接比较两个元素对应的优先级索引差即可,该方案性能远高于每次排序都调用indexOf查找位置,数组量越大优势越明显。
第一部分:一维字符串数组排序
// 构建优先级映射表,查找时间复杂度O(1) const levelPriority = new Map(educationLevel.map((item, index) => [item, index])); // 自定义排序 const educationSorted = education.sort((a, b) => { return levelPriority.get(a) - levelPriority.get(b); });
第二部分:二维嵌套数组排序
仅需要调整取值逻辑,取子数组中存储学历的对应字段(示例中为子数组索引为1的元素)做比较即可:
const levelPriority = new Map(educationLevel.map((item, index) => [item, index])); const educationSorted = education.sort((a, b) => { return levelPriority.get(a[1]) - levelPriority.get(b[1]); });
补充提示
- 如果存在不在
educationLevel里的异常值,可以给默认优先级处理,比如levelPriority.get(a) ?? Infinity,即可让所有异常值排在列表最后; Array.prototype.sort是原地排序,会直接修改原数组,如果需要保留原数组,排序前先做浅拷贝即可:const sorted = [...originArray].sort(...)
内容的提问来源于stack exchange,提问作者AzJ
相关产品推荐
相关产品推荐

