Reputation: 31
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:
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.
Upvotes: 3
Views: 169
Reputation: 189
Javascript doesn't have a zip function natively. 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.
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]);
});
Upvotes: 0
Reputation: 62771
Here's a somewhat lengthy solution (with a much more concise version below). The basic idea is to:
points
array in descending orderpoints
arraynames
arrayvar 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)
Upvotes: 0
Reputation: 41893
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.
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);
Upvotes: 2