js排序(二维数组/英文/中文)方法封装

在实际业务中,往往会碰到排序的问题,今天我就特地梳理下我常用到的几个小方法,放到公共util里能提高不少效率呢!

1.一维数组排序

(1)js原生sort

 

/*
 * @Name 数组排序
 * @Param 
 * list {array} 原始数组
 * mode {string} 默认asc升序 desc降序
 * @Author [email protected]
 */
function sortArray(list,mode='asc'){
	var compare = function(a,b){
        if (mode == 'asc'){
        	return a - b;
        }
        else if (mode == 'desc'){
        	return b - a;
        }
	};
	var res = list.sort(compare);
	return res;
}

var res = sortArray(arr,'desc')
console.log(JSON.stringify(res))

 

(2)快排

 

var count = 0
var arr = [85, 24, 63, 45, 17, 31, 96, 50]
function quickSort(arr){
  if (arr.length <= 1) { return arr; }
  var pivotIndex = Math.floor(arr.length / 2);
  var pivot = arr.splice(pivotIndex, 1)[0];
  var left = [];
  var right = [];
  for (var i = 0; i < arr.length; i++){
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
	count ++
  return quickSort(left).concat([pivot], quickSort(right));
};

var resArr = quickSort(arr)
console.log('排了' + count + '次')
console.log(resArr)

2.二维数组排序

var arr = [  
	{'name' : 'abc','age' : 20},  
	{'name' : 'cde','age' : 19},  
	{'name' : 'dfc','age' : 25},  
	{'name' : 'bde','age' : 21}  
];

/*
 * @Name 数组按照某一项key值排序
 * @Param 
 * list {array} 原始数组
 * property {string} 需要排的属性
 * mode {string} 默认asc升序 desc降序
 * @Author [email protected]
 */
function sortArrayByProperty(list,property,mode='asc'){
	var compare = function(property){
	    return function(a,b){
	        var value1 = a[property];
	        var value2 = b[property];
	        if (mode == 'asc'){
	        	return value1 - value2;
	        }
	        else if (mode == 'desc'){
	        	return value2 - value1;
	        }
	    }
	};
	var res = list.sort(compare(property));
	return res;
}

var res = sortArrayByProperty(arr,'age','asc')
console.log(JSON.stringify(res))

3.字符串排序,按照首字母

 

(1)英文

 

var list = [{name: "bbb"},{name: "ddd"},{name: "aaa"}];
function stringSort(property){
    return function(a,b){
        var value1 = a[property].charCodeAt(0);
        var value2 = b[property].charCodeAt(0);
        return value1 - value2;
    }
}
console.log(JSON.stringify(list.sort(stringSort('name'))));

 

(2)中文

 

var list3 = [{loc: "武汉"},{loc: "北京"},{loc: "上海"},{loc: "天津"}];
function chineseCharacters(property){
    return function(a,b){
        var value1 = a[property].charAt(0);
        var value2 = b[property].charAt(0);
        return value1.localeCompare(value2);
    }
}
console.log(JSON.stringify(list3.sort(chineseCharacters('loc'))));

 

 

 

你可能感兴趣的:(js)