2

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?

5
  • You treat object as arrays. secondary should be something like that : var secondary = [{"id" : 3, "category" : "animals"}, {"id" : 111, "category" : "water"}]; Commented Aug 4, 2011 at 9:41
  • I don't know javascript so I can't give you an answer, but please clarify: do you want to sort by id's, or by the values in the first array, or do you mean according to the order of id's in the first array? Commented Aug 4, 2011 at 9:44
  • @fusion - You RIGHT. it's not an objects, my false. Commented Aug 4, 2011 at 9:46
  • @ymett - according to the order of id's in the first array. Commented Aug 4, 2011 at 9:47
  • Oops.... it's not a duplicate...that was PHP... Commented Aug 4, 2011 at 9:48

2 Answers 2

4

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"]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Just note that calling indexOf for every comparison is quite slow.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.