Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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 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?

like image 698
TIMEX Avatar asked Jun 25 '11 08:06

TIMEX


People also ask

How to sort an array based on the contents of another array?

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 −

How do you modify an array in JavaScript?

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.

What are arrays in JavaScript?

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.

How to swap elements in an array of objects?

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:


1 Answers

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.

like image 159
Mikola Avatar answered Sep 20 '22 23:09

Mikola