JavaScript實現多維陣列多索引值排序方法

來源:互聯網
上載者:User

JavaScript的數組排序函數 sort方法,預設是按照ASCII 字元順序進行升序排列。

arrayobj.sort(sortfunction);

參數:sortFunction

可選項。是用來確定元素順序的函數的名稱。如果這個參數被省略,那麼元素將按照 ASCII 字元順序進行升序排列。

sort 方法將 Array 對象進行適當的排序;在執行過程中並不會建立新的 Array 對象。

如果為 sortfunction 參數提供了一個函數,那麼該函數必須返回下列值之一:

負值,如果所傳遞的第一個參數比第二個參數小。

零,如果兩個參數相等。

正值,如果第一個參數比第二個參數大。

以上的方法在一維的排序還是很方便的,但像SQL語句中的ORDER BY 一樣的多索引值排序由怎麼做呢?

多維陣列的多索引值排序,則需要複雜一些,但不需要用迴圈解決。實際解決的道理是一樣的 。

數字:

以下的例子是將數位多維陣列按照第5列,第9列,第3列的順序排序,像SQL語句中的ORDER BY col5,col9,col7。數位時候可以直接兩個項目相減,以結果作為傳回值即可。

<script language=javascript>
   var myArray = new Array();
   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>

字元:

字元的時候sortFunction中的項目不能像數字一樣直接相減,需要調用

str1.localeCompare( str2 )方法來作比較,從而滿足傳回值。以下是多維陣列的第1,2列作排序的情況。

function sortFunction(array) ...{
   return array.sort( function(x, y) ...{
   return (x[0]==y[0])?(x[1].localeCompare(y[1])):(x[0].localeCompare(y[0]))
   });
}

因此arrayObject.sort( sortFunction )的排序功能還是很強大的,終於能夠實現了SQL語句中的ORDER BY 一樣的功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.