1. 程式人生 > >前端json型別、資料型別陣列如何排序

前端json型別、資料型別陣列如何排序

json型別的陣列如何排序

var result = [{'id':1,'name': 'A1'},{'id':3,'name': 'A3'},{'id':7,'name': 'A7'},{'id':9,'name': 'A9'},{'id':6,'name': 'A6'},{'id':5,'name': 'A5'},{'id':10,'name': 'A10'},{'id':8,'name': 'A8'}];
function sortId(a,b){  
       return a.id-b.id  
    }
    result.sort(sortId);
    console.log(result); 
結果:
0: {id: 1, name: "A1"}
1: {id: 3, name: "A3"}
2: {id: 5, name: "A5"}
3: {id: 6, name: "A6"}
4: {id: 7, name: "A7"}
5: {id: 8, name: "A8"}
6: {id: 9, name: "A9"}
7: {id: 10, name: "A10"}

資料型別的陣列如何排序

var test = [3,1,32,44,23,55,12,21]
var compare = function (x, y) {//比較函式
    if (x < y) {
        return -1;
    } else if (x > y) {
        return 1;
    } else {
        return 0;
    }
}
test.arr(compare)
// 結果是 [1,3,12,21,23,32,44,55]