很抱歉,如果这是一个愚蠢的问题,但我正在学习JavaScript,并且想知道是否有一种简单的方法来排序2个列表,如下所示:
requests.post(..., json=payload)
如何显示名称中的项目'根据“积分”中的相应值?例如,首先显示上面的var names=["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
var points=[12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];
,最后显示item6
。
答案 0 :(得分:2)
我不知道是否足够,但您可以创建一个对象数组,按value
道具对其进行排序,然后只映射以获取{{1}道具。
name
答案 1 :(得分:0)
这是一个有点冗长的解决方案(下面有一个更简洁的版本)。基本思路是:
points
数组points
数组中每个值的位置names
数组
var names=["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
var points=[12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];
const sortedPoints = points.slice().sort(function(a, b) {
return b - a;
});
const sortedNames = [];
sortedPoints.forEach(function(val) {
const position = points.indexOf(val);
sortedNames.push(names[position]);
})
console.log(sortedNames)

要获得更简洁的解决方案,请遵循上述相同的流程,但要利用一些快捷方式:
const names = ["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
const points = [12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];
const sortedNames = points.slice().sort((a, b) => b - a).map(val => names[points.indexOf(val)]);
console.log(sortedNames)

答案 2 :(得分:0)
Javascript本身没有zip功能。但这就是你想要做的大部分事情。像underscore这样的小实用程序库非常方便。如果您只想自己复制zip函数,则可以查看带注释的源。
var zippedAndSorted = _.zip(names, points)
.sort(function(a, b) {
return b - a;
});
然后你可以遍历每一对:
zippedAndSorted.forEach(function(namePoint) {
console.log('Name: ' + namePoint[0] + ' Points: ' + namePoint[1]);
});