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
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]])
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With