排序是開發中不可避免的,最近遇到一個需求須要將JSON數組排序,需求比較簡單,實現起來也沒什麼難度,簡單記錄下過程:json
首先咱們須要明白的JavaScript自己的排序是能夠傳入函數比較的,數組排序以下:數組
var arr = [25, 2, 32, 12, 72, 51, 65, 97, 60, 20]; function descend(a, b) { return a<b ? 1 : -1; } arr.sort(descend);
輸出結果:函數
[ 97, 72, 65, 60, 51, 32, 25, 20, 12, 2 ]//博客園-FlyElephant
JSON數組和數組方法相似,對好比下:this
var json = [{ name: 'keso', age: 25 }, { name: '博客園-FlyElephant', age: 24 }, { name: 'http://www.cnblogs.com/xiaofeixiang/', age: 22 }]; function ascend(a, b) { return (a.age > b.age) ? 1 : -1; } json.sort(ascend); console.log(json);
輸出結果:spa
[ { name: 'http://www.cnblogs.com/xiaofeixiang/', age: 22 }, { name: '博客園-FlyElephant', age: 24 }, { name: 'keso', age: 25 } ]
若是想更好的封裝一下能夠寫成類的形式,類寫法:prototype
function JsonSort(obj, field, sortby) { this.obj = obj; this.field = field; this.sortby = sortby; } JsonSort.prototype.sort= function() { var $this=this; var ascend = function(a, b) { return a[$this.field] > b[$this.field] ? 1 : -1; }; var descend = function(a, b) { return a[$this.field] > b[$this.field] ? -1 : 1; }; if (this.sortby == "ascend") { this.obj.sort(ascend); } else { this.obj.sort(descend); } }; var jsonSort=new JsonSort(json,'age','ascend'); jsonSort.sort(); console.log(json);
若是你有更好的方法,歡迎探討~blog