JavaScript物件陣列根據某屬性sort升降序排序
阿新 • • 發佈:2018-12-11
1、自定義一個比較器,其引數為待排序的屬性。
2、將帶引數的比較器傳入sort()。
var data = [ {name: "Bruce", age: 23, id: 16, score: 80}, {name: "Alice", age: 24, id: 12, score: 90}, {name: "David", age: 21, id: 11, score: 70}, {name: "Cindy", age: 22, id: 10, score: 100},];
data.sort(compareUp("age"));data.sort(compareDown("age"));
function compareUp(propertyName) { // 升序排序 if ((typeof data[0][propertyName]) != "number") { // 屬性值為非數字 return function(object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; return value1.localeCompare(value2);
function compareDown(propertyName) { // 降序排序 if ((typeof data[0][propertyName]) != "number") { // 屬性值為非數字