0.前言
工作中遇到一个需求,需根据从接口拿的json数据,按照某个字段进行排序。比如时间,或者序号等。原始数据如下,需要根据regionCode进行排序。

1.解决办法
上学的时候学过好几种排序算法,但是在实际应用中还是sort比较香。也很简单,直接上代码。
1 2 3 4 5 6 7 8 9 | getAll(){ var res = this .result; res.sort( this .sortRegionCode) console.log(res) } //按照regionCode进行排序 sortRegionCode(a,b){ return a.regionCode -b.regionCode } |
其中res和result是返回的json数据,拍完序之后的结果如下:

可以看出,已经按照regionCode的顺序进行排序了。
2.第二种方法
/**
* 排序共通
* @param sortName 排序字段名称
* @param sortValue 排序顺序 descend ascend null
* @param list 排序数组
* @param sortType 排序类型待扩展
*/
doSort(sortName: string, sortValue: string, list: any[], sortType?: string): [] {
const copyList = JSON.parse(JSON.stringify(list));
if (sortName && sortValue) {
return copyList.sort((a, b) => {
return sortValue === 'ascend' ? (a[sortName!] > b[sortName!] ? 1 : -1) : b[sortName!] > a[sortName!] ? 1 : -1;
});
} else {
return copyList;
}
}
/**
* 排序共通
* @param sortName 排序字段名称
* @param sortValue 排序顺序 descend ascend null
* @param list 排序数组
* @param sortType 排序类型待扩展
*/
doSort(sortName: string, sortValue: string, list: any[], sortType?: string): [] {
const copyList = JSON.parse(JSON.stringify(list));
if (sortName && sortValue) {
return copyList.sort((a, b) => {
return sortValue === 'ascend' ? (a[sortName!] > b[sortName!] ? 1 : -1) : b[sortName!] > a[sortName!] ? 1 : -1;
});
} else {
return copyList;
}
}
/** * 排序共通 * @param sortName 排序字段名称 * @param sortValue 排序顺序 descend ascend null * @param list 排序数组 * @param sortType 排序类型待扩展 */ doSort(sortName: string, sortValue: string, list: any[], sortType?: string): [] { const copyList = JSON.parse(JSON.stringify(list)); if (sortName && sortValue) { return copyList.sort((a, b) => { return sortValue === 'ascend' ? (a[sortName!] > b[sortName!] ? 1 : -1) : b[sortName!] > a[sortName!] ? 1 : -1; }); } else { return copyList; } }
返回目录:前端