js 多維陣列排序是本文章要重點講到的,以前只講一下陣列排序,現在是實現多維資料進行排序,js中的多維陣列可以理解為一個單維陣列,它的每個元素為一個陣列物件,以此類推
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "HTTP://www.w3.org/tr/xhtml1/dtd/ xhtml1-transitional.dtd">
<html xmlns="HTTP://www.w3.org/1999/xhtml">
<head>
<meta HTTP-equiv="content-type" content="text/html; charset=gb2312" />
<title>js 多維陣列排序</title>
<script language=網頁特效>
var myarray = new ar ray();
for(var i=0;i<10;i++ ){
myarray[i]=new array();
myarray[i][0]=math.floor(math.random()*10);
myarray[i][1]=math.floor(math.random()*10);
myarray[i][2]=math.floor(math.random()*10);
myarray[i][3]=math.floor(math.random()*10);
myarray[i][4]=math.floor(math.random()*10);
myarray[i][5]=math.floor(math.random()*10);
myarray[i][6]=math.floor(math.random()*10);
myarray[i][7]=math.floor(math.random()*10);
myarray[i][8]=math.floor(math.random()*10);
}
myarray.sort( function(x, y) {
return (x[0]==y[0])? ((x[4]==y[4])? (x[8]-y[8]):(x[4]-y[4])):(x[2]-y[2])
});
for(var i=0;i<myarray.length;i++ ){
document.write(myarray[i].join(",") + "<br/>");
}
</script>
//再一個經典的js多維資料排序方法代碼吧
var temp = [
{ x:x-1, y:y-1, ct:5, d:0},
{ x:x , y:y-1, ct:2, d:1},
{ x:x+1, y:y-1, ct:7, d:2},
{ x:x+1, y:y, ct:3, d:3},
& nbsp; { x:x+1, y:y+1, ct:0, d:4},
{ x:x, y:y+1, ct:1, d:5},
{ x:x-1, y:y+1, ct:6, d:6},
{ x:x-1, y :y, ct:4, d:7}
];
1、首先你給出的不是多維陣列,js也無多維陣列的概念
2、簡單的應用使用冒泡法就足以勝任,資料量較大時可採用分區法和快速排序法
3、這裡給出冒泡法+回呼函數的代碼,示例為將陣列按ct列昇冪排列
<script>
function cmp(a,b,c) {
if(a[c] == b[c])
return 0;
return a[c] > b[c] ? 1:-1;
}
for(i=0;i <temp.length-1;i++)
for(j=i;j <temp.length;j++)
if(cmp(temp[i],temp[j], "ct ") > 0) {
c = temp[i]
temp[i] = temp[j]
temp[j] = c
}
</script>
</head>
<body>
<body>
<div id=div1> </div> <br>
<button onclick=mysort(0)> sortbycol-1 </button>
<button onclick=mysort(1)> sortbycol-2 </button>
<button onclick=mysort(2)> sortbycol-3 </button>
< button onclick=mysort(3)> sortbycol-4 </button>
<script language= " javascript ">
<!--
var ar=[[75,86,95,64],[66,88,77,99],[86,45,76,85],[94,65,86,70]]
div1.innerhtml = ar.join( " <br> ")
var col=0;
function cmp(a,b){
return a[col]-b[col];
}
function mysort(i){
col = i;
ar = ar.sort(cmp);
div1.innerhtml = ar.join( " <br> ")
}
-->
</script>
</body>
</body>
</html>