陣列排序,物件陣列排序
阿新 • • 發佈:2018-12-09
陣列排序,根據陣列中物件的某一個屬性進行排序
陣列排序
sortlen =[1,9,11,55,3,4]
sortlen = sortlen.sort(function(x,y){
return y-x; //從大到小
})
console.log(sortlen); //[55,11,9,4,3,1]
根據陣列中物件的某一個屬性進行排序
//根據age從小到大排列 var arra=[{"name":"張三","age":16},{"name":"王五","age":6},{"name":"李四","age":14}] var by = function(name){ return function(o, p){ var a, b; if (typeof o === "object" && typeof p === "object" && o && p) { a = o[name]; b = p[name]; if (a === b) { return 0; } if (typeof a === typeof b) { return a < b ? -1 : 1; //從大到小時 對調-1和1的位置 } return typeof a < typeof b ? -1 : 1; } else { throw ("error"); } } } arra=arra.sort(by("age")); console.log(arra) //[{"name":"王五","age":6},{"name":"李四","age":14},{"name":"張三","age":16},]
記錄下