- var arr = [
- {name:'a',age:9},
- {name:'b',age:12},
- {name:'c',age:8}
- ];
- arr.sort((a,b)=>{
- return a.age - b.age
- });
- function compare(property){
- return function(a,b){
- var value1 = a[property];
- var value2 = b[property];
- return value1 - value2;
- }
- }
- console.log(arr.sort(compare('age')))
* 使用例子: newArray.sort(sortBy('number',false)) // 表示根据 number 属性降序排列; 若第二个参数不传递, 默认表示升序排序
* @param attr 排序的属性 如 number 属性
* @param rev true 表示升序排列, false 降序排序
- * */
- sortBy: function(attr,rev){
- // 第二个参数没有传递 默认升序排列
- if(rev == undefined){
- rev = 1;
- }else{
- rev = (rev) ? 1 : -1;
- }
- return function(a,b){
- a = a[attr];
- b = b[attr];
- if(a <b){
- return rev * -1;
- }
- if(a> b){
- return rev * 1;
- }
- return 0;
- }
- }
来源: http://www.bubuko.com/infodetail-3194413.html