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?
We are required to write a sorting function that sort an array based on the contents of another array. For example − We have to sort the original array such that the elements present in the below sortOrder array appear right at the start of original array and all other should keep their order −
An array can be any dimensional (one or multidimensional). The JavaScript array can store anything like direct values or store JavaScript objects. The splice () method mutates or modifies the contents of an original array. This is done by removing, replacing existing items, and adding new items in their place.
The Arrays are an important part of each programming language as they contain many ordered elements. In contrast to other languages, JS Arrays may contain different data types in different indexes of the same matrix. All of these items are accessed through an index.
If you know the indexes you could easily swap the elements, with a simple function like this: Array indexes are just properties of the array object, so you can swap its values. You could always use the sort method, if you don't know where the record is at present: Change 2 to 1 as the first parameter in the splice call when removing the element:
Here is some code that would do it:
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 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.
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