2

Given:

var a1 = [{name:'Scott'}, {name:'John'}, {name:'Albert'}];
var sortOrder = ['John', 'Scott', 'Albert'];

How can I sort the first array (by property) based on the order specified in the second array.

// result: [{name:'John'}, {name:'Scott'}, {name:'Albert'}]

Thanks.

1 Answer 1

7
a1.sort(function(a,b) {
  return (
    sortOrder.indexOf(a.name) < sortOrder.indexOf(b.name) ? -1 : 1
  );
});
Sign up to request clarification or add additional context in comments.

4 Comments

That was what I was in the middle of typing... +1
Only issue here is that IE doesn't support indexOf(), so you'll need to create an indexOf() function for it: stellapower.net/content/javascript-support-and-arrayindexof-ie
@Gert G: either that, or make IE work 'properly' using Chrome Frame ;)
It worked for me, but I have to changed to a1.sort(function(a,b) { return (sortOrder.indexOf(a.name) < sortOrder.indexOf(b.name) ) ? -1 : 1;});

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.