-1
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];
zelocs
  • 25
  • 4
  • 4
    You want the result to be an array of indices? And why do you have the data stored in two separate arrays in the first place instead of an array of objects? – Blue Skies Nov 03 '13 at 21:14
  • 1
    You pose three different questions: (1) your title, (2) your description, and (3) your example. – Paul Draper Nov 03 '13 at 21:22
  • See here: http://stackoverflow.com/questions/17074324/how-can-i-sort-two-vectors-in-the-same-way-with-criteria-that-uses-only-one-of/17074810#17074810 This answer is for C++11, but the concept is directly applicable. – Timothy Shields Nov 03 '13 at 21:24
  • 1
    @TimothyShields, someone converting an answer from one language which they have never seen to another language is not prerequisite. Perhaps something exists in JavaScript which makes this easier. Or maybe there is an idiomatic way to do it that different than in C++11. Also, C++11 is so new that most compilers have it off by default. – Paul Draper Nov 03 '13 at 21:31
  • @PaulDraper There's a reason it was a comment and not an answer. ;) The idea of (A) creating the list containing 1,2,...n, (B) sorting that list based on your key then (C) using the sorted list of indices to permute your list of items is in fact directly applicable... – Timothy Shields Nov 03 '13 at 23:58
  • @TimothyShields, quite correct. I misunderstood your comment as implying that the question was a duplicate of another question. – Paul Draper Nov 04 '13 at 04:01

2 Answers2

2

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];
});
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
2

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}]
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42