开发者

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开发者_JS百科, 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?


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"]);
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜