sort排序
2017-11-09 13:52
260 查看
1、原理
两个元素x和y,若x<y,返回-1;若x==y,返回0;若x>y,返回1。
2、对数字进行排序
var arr = [10,4,20,5,3];
//顺序排列
function ascSort(a,b) {
return a - b;
}
//倒序排列
function descSort(a,b) {
return b - a;
}
arr.sort(ascSort)//[3,4,5,10,10]
arr.sort(descSort)//[20,10,5,4,3]
//数组对象排序
varresult =[{title:
"zx",score:5}, {title:"cyz",score:4}, {title:"wl",score:2},
{title:"zjw",score:3}, {title:"zzf",score:1}];
result.sort(getSortFun('asc','score'));
functiongetSortFun(order,sortBy) {
var ordAlpah =
(order == 'asc') ? '>' : '<';
varsortFun
= new Function('a', 'b', 'return a.'+ sortBy
+ ordAlpah + 'b.' +
sortBy + ' ? 1: -1');
returnsortFun;
}//顺序排列
result.sort(getSortFun('desc', 'score'));
function getSortFun(order, sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?
1: -1');
return sortFun;
}//倒序排列
两个元素x和y,若x<y,返回-1;若x==y,返回0;若x>y,返回1。
2、对数字进行排序
var arr = [10,4,20,5,3];
//顺序排列
function ascSort(a,b) {
return a - b;
}
//倒序排列
function descSort(a,b) {
return b - a;
}
arr.sort(ascSort)//[3,4,5,10,10]
arr.sort(descSort)//[20,10,5,4,3]
//数组对象排序
varresult =[{title:
"zx",score:5}, {title:"cyz",score:4}, {title:"wl",score:2},
{title:"zjw",score:3}, {title:"zzf",score:1}];
result.sort(getSortFun('asc','score'));
functiongetSortFun(order,sortBy) {
var ordAlpah =
(order == 'asc') ? '>' : '<';
varsortFun
= new Function('a', 'b', 'return a.'+ sortBy
+ ordAlpah + 'b.' +
sortBy + ' ? 1: -1');
returnsortFun;
}//顺序排列
result.sort(getSortFun('desc', 'score'));
function getSortFun(order, sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?
1: -1');
return sortFun;
}//倒序排列
相关文章推荐
- sort 及 priority_queu 中struct结构体的重载<排序
- [LintCode] Sort Integers II 整数排序之二
- js使用Array.prototype.sort()对数组对象排序的方法
- php-redis中的sort排序函数总结
- sort()接受一个函数方法进行排序
- 无聊写排序之 ---- 计数排序(CountingSort)
- sort排序,按指定字段进去重,sort -t "^" -k 8 -su
- 问题四:编写模板函数sort,功能是:对三个形参a, b, c按照从大到小排序。
- C++ 排序函数 sort(),qsort()的用法
- [LeetCode]85. Insertion Sort List链表插入排序
- [LeetCode] 75. Sort Colors 颜色排序
- Map按键排序(sort by key), 按值排序(sort by value)。
- js sort根据数值大小自动排序(转)
- 二维数组排序 sort
- STL之sort、priority_queue 排序
- ADO组件可以用SORT进行排序
- 【编程】TreeMap和TreeSet在排序时如何比较元素?Collections工具类中的sort()方法如何比较元素?
- 关于sort 多字段排序
- 类别sort使用排序
- Arrays.sort 字符串排序