How to reorder this array in Javascript based on another array?

real_order = [ '1', '2', '3', '4']; friends = [ { name: 'jess', id: '4'}, { name: 'alex', id: '1'}, { name: 'kat', id: '3' }, { name: 'bob', id: '2' } ] 

How to make an array of friends mapped to elements in real_order ? The result should be:

 [ { name: 'alex', id: '1'}, { name: 'bob', id: '2' }, { name: 'kat', id: '3' }, { name: 'jess', id: '4'}, ] 

What is the most effective solution?

+6
source share
4 answers

Here is the code that would do this:

 var i, d = {}, result = []; for(i=0; i<friends.length; ++i) { d[friends[i].id] = friends[i]; } for(i=0; i<real_order.length; ++i) { result.push(d[real_order[i]]); } 

What he does is create a dictionary associated with each of the friends ids, then use the second array to search and build a new array. The resulting reordered array is saved as a result.

+5
source

Arrays can be sorted using their own sorting algorithm, so you don't need real_order . So I would do it ( edit : added a sort delegate to sort in descending order):

 var friends = [ { id:4, name: 'jess'}, { id:1, name: 'alex'}, { id:3, name: 'kat' }, { id:2, name: 'bob' } ]; var order = function(a,b,desc){ return desc ? b.id - a.id : a.id - b.id; }, orderDesc: function(a,b){return order(a,b,true);}; var friendsOrdered = friends.sort( order ); alert(friendsOrdered[0].name); //=> alex alert(friendsOrdered[3].name); //=> jess //or sort descending var friendsOrdered = friends.sort( orderDesc ); alert(friendsOrdered[0].name); //=> jess alert(friendsOrdered[3].name); //=> alex 
+4
source

make sure that real_order is in global scope and this should do it:

 friends.sort(function(a, b) { if (real_order.indexOf(a.id) > real_order.indexOf(b.id)) { return 1; }else{ return -1; } }); 
0
source

One team decision. Awful like jQuery, but people like John Resig love this style for some reason :)

 friends.sort( (function(order){ return function(a, b) { return order.indexOf(a.id)-order.indexOf(b.id); } })(real_order) ); 
0
source

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


All Articles