Javascript sorting 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 used .sort with a function before, but I still don't get it.

UPDATE

having seen some answers, I cannot believe that this was not obvious to me. Since there are many ways to do this, the winner will be determined by jsperf.

(I also support everyone with a working answer)

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

+4
source share
4 answers

order is an array of pointers. So just iterate over it, pulling the desired values ​​in spcified order, creating 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 is not sorted. Sometimes you just need to do something new by pulling data from other things.

+2
source
 sorted = [] order.forEach(function(i) { sorted.push(people[i]) }); 

or, more bizarre but less readable (IMO):

 sorted = order.reduce(function(r, i) { return r.concat([people[i]]) }, []); 
+6
source

Another way :)

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

jsFiddle .

+4
source

Don't know something like this?

 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]; } 
+1
source

Source: https://habr.com/ru/post/1443116/


All Articles