Luis
Luis

Reputation: 3277

Sorting an array according to another array

I have two arrays, the main includes something like 300 values:

var main = [ 182, 928, 192, 111, 493, 1100, 3 ] ..

The secondary includes 10 values, but each value is an array:

var secondary = [{"id" : 3, "category" : "animals"}, {"id" : 111, "category" : "water"}] ..

My question is how can I sort the secondary array by his id's according to the values in the main array?

Upvotes: 2

Views: 186

Answers (2)

Felix Kling
Felix Kling

Reputation: 816282

First, create some kind of inverted index for the main array:

var main_map = {};
for(var i = main.length;i--; ) {
    main_map[main[i]] = i;
}

Then you can pass a custom sort function to sort [docs] like this:

secondary.sort(function(a, b) {
    return main_map[a["id"]] - main_map[b["id"]];
});

Alternatively, you could create an inverted index for the secondary array and loop over the main array, but as your secondary array is much smaller, this would be less efficient.

Upvotes: 0

fusion
fusion

Reputation: 1287

You could use the following code if you structure the second array as mentioned. The solution uses indexOf which may not be present in all browsers. Mozilla provides an implementation for indexOf here.

var main = [ 182, 928, 192, 111, 493, 1100, 3 ];
var secondary = [{"id" : 3, "category" : "animals"}, {"id" : 111, "category" : "water"}];

secondary.sort(function(a, b) {
    return main.indexOf(a["id"]) - main.indexOf(b["id"]);
});

Upvotes: 4

Related Questions