数组排序
现在很多前端工具都有封装好排序,但是没有的话,反反复复写,就会感觉很烦,所以…
代码?
借鉴了大大,稍作修改
function arrMinNum(arr) {
var minNum = Infinity, index = -1, minVul = "";
var reg = /^[0-9]+\.?[0-9]*$/ //正则判断数字
for (var i = 0; i < arr.length; i++) {
if(reg.test(arr[i])){
if ( parseInt(arr[i]) < minNum) { //数字转换
minNum = arr[i];
minVul = arr[i]
index = i;
}
}else{
if (arr[i].charCodeAt() < minNum) { //文本转换
minNum = arr[i].charCodeAt();
minVul = arr[i];
index = i;
}
}
};
return {"minNum": minVul, "index": index};
}
function arrSortMinToMax(arr){
var arrNew = [];
var arrOld = arr.concat();
for (var i = 0; i < arr.length; i++) {
arrNew.push(arrMinNum(arrOld).minNum);
arrOld.splice(arrMinNum(arrOld).index,1)
};
return (arrNew);
}
function arrMaxNum(arr){
var maxNum = -Infinity, index = -1,maxVul = "";
var reg = /^[0-9]+\.?[0-9]*$/
for (var i = 0; i < arr.length; i++) {
if(reg.test(arr[i])){
if ( parseInt(arr[i])>maxNum) {
maxNum = arr[i];
maxVul = arr[i];
index = i;
}
}else{
if (arr[i].charCodeAt()>maxNum) {
maxNum = arr[i].charCodeAt();
maxVul = arr[i];
index = i;
}
}
};
return {"maxNum":maxVul,"index":index};
}
function arrSortMaxToMin(arr) {
var arrNew = [];
var arrOld = arr.slice(0);
for (var i = 0; i < arr.length; i++) {
arrNew.push(arrMaxNum(arrOld).maxNum);
arrOld.splice(arrMaxNum(arrOld).index, 1);
};
return (arrNew);
}