real_order = [ '1', '2', '3', '4'];
friends = [ { name: 'jess', id: '4'},
{ name: 'alex', id: '1'},
{ name: 'kat', id: '3' },
{ name: 'bob', id: '2' }
]
How do I make “friends” array “match” the 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 efficient solution?
Here is some code that would do it:
What this does is it creates a dictionary keyed on each of the friends’ id, then uses the second array to do a look up and construct the new array. The resulting reordered array is stored in result.