如何用JavaScript根据权重数组对单词数组降序排序?求替代方案
按权重降序排序单词数组的替代方案
你原来用weights.indexOf(b) - weights.indexOf(a)的排序方法有个明显的坑:如果权重数组里存在重复值,indexOf只会返回第一个匹配项的索引,直接导致排序结果混乱。下面给你几个靠谱的替代方案:
方案一:配对后排序(最稳妥)
把单词和对应的权重绑定成对象,排序完成后再提取单词,不管权重或单词有没有重复都能正常工作:
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; let weights = [2, 1, 3, 4, 6, 5]; // 将单词与对应权重配对成对象数组 const pairedList = words.map((word, idx) => ({ word, weight: weights[idx] })); // 按权重降序排序 pairedList.sort((x, y) => y.weight - x.weight); // 提取排序后的单词数组 const sortedWords = pairedList.map(item => item.word); console.log(sortedWords); // 输出: ['acdcc', 'acbcc', 'abef', 'abaa', 'abcd', 'aecd']
方案二:通过索引直接关联排序(适合无重复单词的场景)
如果你的words数组里没有重复单词,可以直接用原数组的索引获取对应权重,避开indexOf的缺陷:
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; let weights = [2, 1, 3, 4, 6, 5]; // 先复制原数组避免修改原数据(不需要保留原数组的话可直接调用sort) const sortedWords = [...words].sort((a, b) => { const idxA = words.indexOf(a); const idxB = words.indexOf(b); return weights[idxB] - weights[idxA]; }); console.log(sortedWords); // 输出同上
方案三:用Array.from带索引处理
和方案一思路类似,借助Array.from生成带索引的结构,排序后提取单词:
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; let weights = [2, 1, 3, 4, 6, 5]; const sortedWords = Array.from(words, (word, idx) => ({ word, idx })) .sort((x, y) => weights[y.idx] - weights[x.idx]) .map(item => item.word); console.log(sortedWords); // 输出同上
内容的提问来源于stack exchange,提问作者Ashy Ashcsi
相关产品推荐
相关产品推荐

