前端json类型、数据类型数组如何排序
2018-10-26 本文已影响9人
奋斗滴猩猩
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]