JavaScript多维数组多键值排序方法实现


  本文标签:JavaScript 多维数组

  你对JavaScript实现多维数组多键值排序方法是否熟悉 ,这里和大家分享一下,JavaScript的数组排序函数sort方法,默认是按照ASCII字符顺序进行升序排列  。

  JavaScript实现多维数组多键值排序方法

  JavaScript的数组排序函数sort方法,默认是按照ASCII字符顺序进行升序排列  。

  arrayobj.sort(sortfunction);

  参数:sortFunction

  可选项  。是用来确定元素顺序的函数的名称  。如果这个参数被省略,那么元素将按照ASCII字符顺序进行升序排列  。

  sort方法将Array对象进行适当的排序;在执行过程中并不会创建新的Array对象  。

  如果为sortfunction参数提供了一个函数,那么该函数必须返回下列值之一:

  负值,如果所传递的第一个参数比第二个参数小  。

  零,如果两个参数相等  。

  正值,如果第一个参数比第二个参数大  。

  以上的方法在一维的排序还是很方便的,但像SQL语句中的ORDERBY一样的多键值排序由怎么做呢?

  多维数组的多键值排序,则需要复杂一些,但不需要用循环解决  。实际解决的道理是一样的  。

  数字:

  以下的例子是将数字的多维数组按照第5列,第9列,第3列的顺序排序,像SQL语句中的ORDERBYcol5,col9,col7  。数字的时候可以直接两个项目相减,以结果作为返回值即可  。

  1. <scriptlanguagescriptlanguage=javascript> 
  2. varmyArray=newArray();  
  3. for(vari=0;i<10;i++)...{  
  4. myArray[i]=newArray();  
  5. myArray[i][0]=Math.floor(Math.random()*10);  
  6. myArray[i][1]=Math.floor(Math.random()*10);  
  7. myArray[i][2]=Math.floor(Math.random()*10);  
  8. myArray[i][3]=Math.floor(Math.random()*10);  
  9. myArray[i][4]=Math.floor(Math.random()*10);  
  10. myArray[i][5]=Math.floor(Math.random()*10);  
  11. myArray[i][6]=Math.floor(Math.random()*10);  
  12. myArray[i][7]=Math.floor(Math.random()*10);  
  13. myArray[i][8]=Math.floor(Math.random()*10);  
  14. }  
  15.  
  16. myArray.sort(function(x,y)...{  
  17. return(x[0]==y[0])?((x[4]==y[4])?(x[8]-y[8]):(x[4]-y[4])):(x[2]-y[2])  
  18. });  
  19. for(vari=0;i<myArray.length;i++)...{  
  20. document.write(myArray[i].join(",")+"<br/>");  
  21. }  
  22. script> 
  23.  

  字符:

  字符的时候sortFunction中的项目不能像数字一样直接相减,需要调用

  str1.localeCompare(str2)方法来作比较,从而满足返回值  。以下是多维数组的第1,2列作排序的情况  。

  1. functionsortFunction(array)...{  
  2. returnarray.sort(function(x,y)...{  
  3. return(x[0]==y[0])?(x[1].localeCompare(y[1])):(x[0].localeCompare(y[0]))  
  4. });  

  因此arrayObject.sort(sortFunction)的排序功能还是很强大的,终于能够实现了SQL语句中的ORDERBY一样的功能  。