[英]Easy way to sort 2 arrays in Javascript?
Sorry if this is a stupid question, but I'm learning JavaScript and was wondering if there was an easy way to sort 2 lists like the ones here: 很抱歉,如果这是一个愚蠢的问题,但我正在学习JavaScript,并想知道是否有一种简单的方法来排序2个列表,如下所示:
var names=["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
var points=[12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];
How would I display the items from 'names' according to the corresponding value in 'points'? 如何根据“点数”中的相应值显示“名称”中的项目? For example, for the above
item6
would displayed first and item5
would be displayed last. 例如,对于上面的项目
item6
将首先显示,而item5
将最后显示。
I don't know if it's easy enough , but you could make an array of objects, sort it by the value
prop and just map to get only the name
props. 我不知道它是否足够简单 ,但你可以创建一个对象数组,按
value
道具对它进行排序,然后只绘制地图以获得name
道具。
let names = ["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"], points = [12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101], res = names.map((v, i) => ({ name: v, val: points[i] })) .sort((a, b) => b.val - a.val) .map(v => v.name); console.log(res);
Here's a somewhat lengthy solution (with a much more concise version below). 这是一个有点冗长的解决方案(下面有一个更简洁的版本)。 The basic idea is to:
基本思路是:
points
array in descending order points
组进行排序 points
array points
组中查找每个值的位置 names
array 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)
For a more concise solution, following the same process above but taking advantage of some shortcuts: 有关更简洁的解决方案,请遵循上述相同的过程,但要利用一些快捷方式:
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)
Javascript doesn't have a zip function natively. Javascript本身没有zip函数。 But that is most of what you want to do here.
但这就是你想要做的大部分事情。 A little utility library like underscore is pretty handy.
像下划线这样的小实用程序库非常方便。 You can view the annotated source if you just want to replicate a zip function yourself.
如果您只想自己复制zip函数,则可以查看带注释的源。
var zippedAndSorted = _.zip(names, points)
.sort(function(a, b) {
return b - a;
});
Then you can iterate over each pair: 然后你可以遍历每一对:
zippedAndSorted.forEach(function(namePoint) {
console.log('Name: ' + namePoint[0] + ' Points: ' + namePoint[1]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.