繁体   English   中英

javascript 根据来自另一个数组的权重对单词数组进行排序

[英]javascript sort an array of words based on weights from another array

我有一个与之关联的字符串和权重数组,如下所示:

const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc'];
let weights = [2, 1, 3, 4, 6, 5];

我想根据它们在另一个数组中的权重按降序对单词进行排序。 我尝试了以下解决方案:

words.sort((a, b) =>
    weights.indexOf(b) -
    weights.indexOf(a));

任何人都可以提出替代解决方案。

谢谢

我认为解决这个问题的最简单方法是将单词和权重组合到一个数组中,然后对该数组进行排序。

 const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; const weights = [2, 1, 3, 4, 6, 5]; const result = words.map((word, i) => ({ word, weight: weights[i] })).sort((a, b) => a.weight - b.weight).map(({ word }) => word); console.log(result);

我认为您正在寻找weights[words.indexOf(b)] ,而不是 weights.indexOf( weights.indexOf(b) (尽管这仅在words中的值是唯一的情况下才有效):

 const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; let weights = [2, 1, 3, 4, 6, 5]; words.sort((a, b) => weights[words.indexOf(b)] - weights[words.indexOf(a)]); console.log(words)

要详细了解事情是如何工作的,请参阅下面的代码。

 const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc']; let weights = [2, 1, 3, 4, 6, 5]; var weights1 = []; let words1 = []; weights.forEach(function(a) { weights1.push(a); }); weights.sort(function(a, b) { return a - b; }); weights.forEach(function(a) { words1.push(words[weights1.indexOf(a)]); }); console.log(words1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM