如何基于自定义后置查找列表实现数组的自定义排序
实现方案
该需求完全可以通过自定义Array.sort的比较函数实现,核心逻辑是给需要后置的元素设置更高的排序权重,排序时优先按权重分组,同权重下按常规规则排序即可。
基础实现(同组内按字典序排序)
const input_place_last_lookup = ["not","in"]; const input_array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]; input_array.sort((a, b) => { const aNeedPlaceLast = input_place_last_lookup.includes(a); const bNeedPlaceLast = input_place_last_lookup.includes(b); // 只有一个需要后置时,不需要后置的元素排前面 if (aNeedPlaceLast && !bNeedPlaceLast) return 1; if (!aNeedPlaceLast && bNeedPlaceLast) return -1; // 同组内按默认字典序排序 return a.localeCompare(b); });
匹配示例预期输出的实现(后置元素按lookup配置顺序排列)
如果需要后置的元素严格按照place_last_lookup内的顺序排列,可调整权重计算规则,就能完全匹配你给出的输出结果:
const input_place_last_lookup = ["not","in"]; const input_array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]; input_array.sort((a, b) => { const getSortWeight = (item) => { const indexInLookup = input_place_last_lookup.indexOf(item); // 非后置元素权重为0,后置元素按在lookup中的顺序分配1、2...的权重 return indexInLookup === -1 ? 0 : indexInLookup + 1; } const weightA = getSortWeight(a); const weightB = getSortWeight(b); // 权重不同时按权重升序排,权重相同时按字典序排 if (weightA !== weightB) return weightA - weightB; return a.localeCompare(b); }); // 最终输出:["all", "are", "good", "programmers", "the", "world", "not", "in"]
内容的提问来源于stack exchange,提问作者user16731842
相关产品推荐
相关产品推荐

