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'))));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章