Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Here is an example:

            //    0     1       2      3       4
 var people = ['jack','jill','nancy','tom','cartman'];
 var order  = [3,1,4,0,2];

 // somehow sort people array to the order specified in the order array

          //  3      1       4        0      2
 people == ['tom','jill','cartman','jack','nancy'];

I have used .sort with a function before, but am still at a loss on this one.

UPDATE

after seeing some answers, I can't believe this was not obvious to me. So as there are many ways to do this, winner will be determined by jsperf.

(also I am upvoting everyone with a working answer)

The RACE! http://jsperf.com/array-sorted-to-order-array3

share|improve this question
2  
Winner should be determined by readability and clearest of intent first :) – alex Oct 30 '12 at 23:20
1  
@Fresheyeball: You mean it's equally functional in your situation. It isn't in all situations. – I Hate Lazy Oct 30 '12 at 23:43
1  
@Fresheyeball Depends on what else is pointing to that original array. – alex Oct 30 '12 at 23:47
1  
@Fresheyeball: If you replace the Array referenced by the people variable, you're only updating that one reference. If there are other references to the original Array, they won't automatically be updated to reference the new Array, so your references will be out of sync. All depends on what's needed. – I Hate Lazy Oct 30 '12 at 23:47
1  
I did not think of the pointer situation. Good point. – Fresheyeball Oct 30 '12 at 23:52
show 7 more comments

4 Answers

up vote 2 down vote accepted

order is an array of indicies. So just iterate through that, pulling out the values you want in the order spcified, making a new array.

var people = ['jack','jill','nancy','tom','cartman'];
var order  = [3,1,4,0,2];

var sorted = [];
for (var i = 0; i < order.length; i++) {
  var desiredIndex = order[i];
  sorted.push(people[desiredIndex]);
}

console.log(sorted);
// ["tom", "jill", "cartman", "jack", "nancy"]

Sometimes sorting isn't "sorting". Sometimes you just need to make a new thing by pulling data from your other things.

share|improve this answer
you win the jsperf performance benchmark, oddly enough – Fresheyeball Oct 30 '12 at 23:38
@Fresheyeball I don't think it's odd. Dropping back to basic constructs such as a for loop is generally fastest. – alex Oct 30 '12 at 23:41
@alex it shouldn't be though. With all the hype surrounding map and reduce, I thought the browser had a way of optimizing this kind of operation far beyond the basic construct. – Fresheyeball Oct 30 '12 at 23:43
@Fresheyeball: It's mostly just that those functional approaches provide nice clean code. The functions can also be stored and reused for different situations. But functions require some overhead to invoke, so a traditional for loop is the way to go when speed is a high priority. – I Hate Lazy Oct 30 '12 at 23:52
Functionless iteration is usually fastest. Even if it is more verbose. – Alex Wayne Oct 30 '12 at 23:54

Just another way :)

people = order.map(function(value) { return people[value]; });

jsFiddle.

share|improve this answer
.map() is the only way to do this IMO. – I Hate Lazy Oct 30 '12 at 23:30
nice........... – thg435 Oct 30 '12 at 23:39
sorted = []
order.forEach(function(i) { sorted.push(people[i]) });

or, more fancy but less readable (IMO):

sorted = order.reduce(function(r, i) { 
    return r.concat([people[i]])
}, []);
share|improve this answer
A much better solution. – enhzflep Oct 30 '12 at 23:16
+1. What a champion!!!!! – Tariqulazam Oct 30 '12 at 23:17
3  
I think alex's is much clearer – Juan Mendes Oct 30 '12 at 23:26
This actually had the worst performance overall. – Fresheyeball Oct 30 '12 at 23:39

I dunno, something like this perhaps?

var people = ['jack','jill','nancy','tom','cartman'];
var order  = [3,1,4,0,2];


var result = [], i, n=order.length;

for (i=0; i<n; i++)
{
  result[ order[i] ] = people[i];
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.