这种相关排序方式是否可以安全使用?

时间:2017-09-24 17:43:01

标签: javascript arrays sorting

我有两个数组。第一个包含单词,第二个包含权重。它们与指数相关联。我如何通过第二个数组对这些数组进行排序,保持关联?

以下是我的尝试:



let words = [
  'car',
  'house',
  'sky',
  'dog',
  'wheel',
  'man',
  'tree',
  'earth'
];

let weights = [
  10,
  43,
  23,
  95,
  55,
  41,
  29,
  84
];

let memory = [];

weights.sort((a, b) => {
  memory.push(b - a);
  return memory[memory.length - 1];
});

words.sort(() => memory.shift());

for (let i = 0; i < words.length; i++) {
  console.log(words[i], weights[i]);
}
&#13;
&#13;
&#13;

它似乎工作正常。但我担心它可能不起作用。这种方式在理论上是否正确?

注意!我没有要求您修改我的算法。我问你,说出这种分类的可能错误。

2 个答案:

答案 0 :(得分:0)

您可以获取索引为weights的数组,并使用索引值对其进行排序,并通过获取已排序的索引数组来映射结果。

基本上这是sorting with map

var words = ['car', 'house', 'sky', 'dog', 'wheel', 'man', 'tree', 'earth'],
    weights = [10, 43, 23, 95, 55, 41, 29, 84],
    temp = weights
        .map((_, i) => i)
        .sort((a, b) => weights[b] - weights[a]),
    result_words = temp.map(i => words[i]),
    result_weights = temp.map(i => weights[i]);

console.log(result_words.map((a, i) => [a, result_weights[i]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以在排序中使用当前单词元素的索引,然后根据具有相同索引的权重的元素值进行排序。

let words = ["car", "house", "sky", "dog", "wheel", "man", "tree", "earth"]
let weights = [ 10, 43, 23, 95, 55, 41, 29, 84 ]

var result = words
  .map((e, i) => e + ' ' + weights[i])
  .sort(function(a, b) {
    var a = a.split(' ').shift(), b = b.split(' ').shift()
    return weights[words.indexOf(b)] - weights[words.indexOf(a)]
  })

console.log(result)

相关问题