var names = ['Bob', 'Joe', 'Phil', 'Max'];
var ages = [8, 23, 15, 17];
I need to sort the names by their age. So something like:
var result = [1, 3, 2, 0];
var names = ['Bob', 'Joe', 'Phil', 'Max'];
var ages = [8, 23, 15, 17];
I need to sort the names by their age. So something like:
var result = [1, 3, 2, 0];
You question asked to sort names, but your output has indices. I'm not sure which you want.
This sorts names by age (per your question):
var sortedNames = ages.map(function(age, i) {
return {age:age, i:i};
}).sort(function(a, b) {
return a.age - b.age;
}).map(function(a) {
return names[a.i];
});
This sorts the indices (per your example):
var result = ages.map(function(age, i) {
return i;
}).sort(function(i, j) {
return ages[i] - ages[j];
});
I would reccommend changing your data structure to something like this
people = [
{name: "John", age: 62},
{name: "Mike", age: 21},
{name: "Dave", age: 54}
];
people.sort(function(val1, val2) {
return val2.age - val1.age;
});
people;//[{name:"John", age:62}, {name:"Dave", age:54}, {name:"Mike", age:21}]