javascript 实现数组或对象排序

来源:互联网 发布:mac 图片转文字 编辑:程序博客网 时间:2024/05/21 06:35

手头上在跟进一个在移动端显示统计分析的需求,其中有一个表格需要支持排序。拿到需求后就上网各种搜控件,没有搜到合适的控件(不知道是不是我搜的姿势不对!求前端大神救救我这个java菜鸟!!),就直接手写了。

/*** collections  集合* fieldName 排序字段* sortType      排序类型 asc:升序  desc:降序  */function sort(collections, fieldName, sortType) {if(!collections) return;sortType = sortType || 'asc';var length = collections.length;var tempObj = {};var tempIndex = 0;var calculateResult = 0;for(var index = 1; index <= length-1; index++){  tempIndex = index;  while(tempIndex-1>=0){      calculateResult = collections[tempIndex][fieldName]-collections[tempIndex-1][fieldName];      if(sortType=='desc' && calculateResult > 0){          tempObj = collections[tempIndex];          collections[tempIndex] = collections[tempIndex-1];          collections[tempIndex-1] = tempObj;      }else if(sortType=='asc' && calculateResult < 0){          tempObj = collections[tempIndex];          collections[tempIndex] = collections[tempIndex-1];          collections[tempIndex-1] = tempObj;      }else{          break;      }      tempIndex--;  }     }//查看排序后的结果for(var item in collections){console.log(collections[item]);}}

测试数据

var collections = [     {'station':'分局1', 'collectNum':4, 'importance':154, 'aqyh':98, 'wfzl':23 },     {'station':'分局2', 'collectNum':90, 'importance':543, 'aqyh':8, 'wfzl':23 },     {'station':'分局3', 'collectNum':48, 'importance':154, 'aqyh':98, 'wfzl':23 },     {'station':'分局4', 'collectNum':21, 'importance':14, 'aqyh':9, 'wfzl':23 },     {'station':'分局5', 'collectNum':79, 'importance':14, 'aqyh':9, 'wfzl':23 } ];
    sort(collections, 'collectNum', 'asc');    console.log("<================>");    sort(collections, 'collectNum', 'desc');

这里写图片描述