數組排序
現在很多前端工具都有封裝好排序,但是沒有的話,反反複複寫,就會感覺很煩,是以…
代碼?
借鑒了大大,稍作修改
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);
}