Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sort array to align with order array

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

like image 945
Fresheyeball Avatar asked Dec 12 '22 21:12

Fresheyeball


1 Answers

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]])
}, []);
like image 59
georg Avatar answered Dec 24 '22 00:12

georg