views:

33

answers:

1

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.

+2  A: 
a1.sort(function(a,b) {(sortOrder.indexOf(a.name) < sortOrder.indexOf(b.name) ? -1 : 1);});
sje397
That was what I was in the middle of typing... +1
Mark
Only issue here is that IE doesn't support `indexOf()`, so you'll need to create an `indexOf()` function for it: http://stellapower.net/content/javascript-support-and-arrayindexof-ie
Gert G
@Gert G: either that, or make IE work 'properly' using [Chrome Frame](http://code.google.com/chrome/chromeframe/) ;)
sje397