[javascript] 二維陣列的排序
var a = [ {name:'hdj', filename:20140930174726.jpg}, {name:'yim', filename:1_title.jpg}, {name:'hdq', filename:20150930174726.jpg}, {name:'rrr', filename:3_title.jpg}, {name:'ddd', filename:2_title.jpg}, ];希望根據 filename 來進行排序,可以使用底下的 function
function listSortBy(arr, field, order){
var refer = [], newrefer = [], comp_arr
=[], result=[];
var order = order=='asc'?'asc':'desc', index;
for(i=0; i<arr.length;
i++){
// 1_title.jpg 20140930174726.jpg
var delExt = arr[i][field].split(".");
// 1_title 20140930174726
var name = delExt[0].split("_");
if (typeof(name[1]) == 'undefined') {
refer[delExt[0]] = i;
comp_arr[i] = delExt[0];
}
else {
refer[name[0]] = i;
comp_arr[i] = name[0];
}
}
if(order=='desc') {
comp_arr.sort(function(a,b){return b-a});
} else {
comp_arr.sort(function(a,b){return a-b});
}
for(i=0; i<comp_arr.length;
i++){
for (var key in refer) {
if (key == comp_arr[i]) {
newrefer[i] = refer[key];
}
}
}
for(i=0;i<newrefer.length;i++){
index = newrefer[i];
result[i] = arr[index];
}
return result;
}
a = listSortBy(a, 'filename', 'desc');
得到的結果為
var a = [ {name:'hdq', filename:20150930174726.jpg}, {name:'hdj', filename:20140930174726.jpg}, {name:'yim', filename:1_title.jpg}, {name:'ddd', filename:2_title.jpg}, {name:'rrr', filename:3_title.jpg}, ];此 function 只適用於數字大小的排序,若要排序字母請修正此行
if(order=='desc') { comp_arr.sort(function(a,b){return b-a}); } else { comp_arr.sort(function(a,b){return a-b}); }改成用
comp_arr.sort(); if(order=='desc') comp_arr.reverse();PS.字母的排序並沒驗證
留言
張貼留言