2010-08-13 67 views
2

的顺序给出:的javascript - 排序的第二阵列

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

如何可以在第一阵列(由属性)基于排序的第二阵列中指定的顺序上。

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

谢谢。

回答

7
a1.sort(function(a,b) { 
    return (
    sortOrder.indexOf(a.name) < sortOrder.indexOf(b.name) ? -1 : 1 
); 
}); 
+0

那正是我在打字的中间...... +1 – Mark 2010-08-13 00:13:08

+0

这里唯一的问题是,IE不支持'的indexOf()',所以你需要创建一个'的indexOf() '功能为:http://stellapower.net/content/javascript-support-and-arrayindexof-ie – 2010-08-13 00:28:17

+0

@Gert G:要么,或使IE浏览器正常使用[Chrome Frame](http:// code .google.com/chrome/chromeframe /);) – sje397 2010-08-13 00:56:26