您的位置:首页 > Web前端 > JavaScript

javascript 实现数组或对象排序

2017-10-24 18:54 253 查看
手头上在跟进一个在移动端显示统计分析的需求,其中有一个表格需要支持排序。拿到需求后就上网各种搜控件,没有搜到合适的控件(不知道是不是我搜的姿势不对!求前端大神救救我这个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');


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: