如何在JavaScript中对数组进行排序

时间:2011-12-28 05:55:27

标签: javascript jquery sorting

我没有使用关联数组。我正在使用这样的1d数组,

array("1,a","5,b","2,c","8,d","6,f");

如何对此数组进行排序?

结果应该是,

array("1,a","2,c","5,b","6,f","8,d");

9 个答案:

答案 0 :(得分:4)

没有自定义排序功能的

sort()会根据您的意愿对其进行排序(按字典顺序排列)。

>>> ["1,a","5,b","2,c","8,d","6,f"].sort();
["1,a", "2,c", "5,b", "6,f", "8,d"]

请注意,这将对原始数组进行排序。您可以使用slice()制作浅表副本。

如果您的任何数字大于9,并且您想通过数字的序数对其进行排序,则需要自定义排序功能。

["1,a","5,b","2,c","8,d","6,f"].sort(function(a, b) {
    return parseInt(a, 10) - parseInt(b, 10);
});

答案 1 :(得分:2)

使用array.sort()内置JS函数。这里的文档:http://www.w3schools.com/jsref/jsref_sort.asp

答案 2 :(得分:1)

http://jsfiddle.net/Dht33/

var arrayVar = ["1,a","2,c","5,b","6,f","8,d"];

arrayVar.sort()

arrayVar; // "1,a","2,c","5,b","6,f","8,d"

答案 3 :(得分:1)

尝试:

function sortNumber(a,b)
{
return (a.split(","))[0] - (b.split(","))[0] ;
}

var n = ["1,a","5,b","2,c","8,d","6,f"];
alert( n.sort(sortNumber) );

答案 4 :(得分:1)

这就是我的所作所为:

var arr1 = new Array("1,a","5,b","2,c","8,d","6,f");
var arr2 = arr1.sort( function(a, b){
    var ax = a.split(",");
    var bx = b.split(",");
    return ax[0]-bx[0];
});

document.getElementById("result").innerHTML = arr2.join(" : ");

答案 5 :(得分:1)

您需要编写自己的比较函数来比较数字,否则默认sort()会在"40,a"之前加上"5,b"之类的内容。

这是一个只在,字符上拆分并假设它之前的值为数字的示例。我在示例中添加了"40,a",以表明它正确地命令了数字>。

function mySort(a,b)
{
    return a.split(",", 1) - b.split(",", 1);
}

var theArray = ["1,a", "5,b", "2,c", "40,a", "8,d", "6,f"];
theArray.sort(mySort); // "1,a","2,c","5,b","6,f","8,d","40,a"

答案 6 :(得分:1)

我将继续并假设您要先按数字部分排序,按数字排序,然后在逗号后面的位上进行二级词法(字符串)排序。这样一个像“11,a”这样的值将在“2,a”之后结束 - 如果你只是做一个默认排序“11,a”将在“2,a”之前结束。所以:

var a = ["1,a","11,a","8,a","24,z","5,b","2,c","8,d","6,f"];

a.sort(function(a,b) {
   var aparts = a.split(","),
       bparts = b.split(","),
       anum = +aparts[0], // convert first part to number
       bnum = +bparts[0],
       aletter = aparts[1],
       bletter = bparts[1];

   if (anum === bnum)
      return aletter < bletter ? -1 : aletter === bletter ? 0 : -1;
   else
      return anum - bnum;
});

结果:

["1,a", "2,c", "5,b", "6,f", "8,a", "8,d", "11,a", "24,z"]

答案 7 :(得分:1)

试试这个

<script>
var abc=new Array("1,a","5,b","2,c","8,d","6,f");
document.write("<br/>");
document.write(abc.sort());
</script>

答案 8 :(得分:0)

试试这个:

<script type="text/javascript">
var testArray = new Array();
testArray[0] = '1';
testArray[1] = '5';
testArray[2] = '9';
testArray[3] = '8';
testArray[4] = '6';
testArray[5] = '2';
var getlength = testArray.length;
testArray.sort(function(a,b){return a - b});
for(var i=0; i<getlength;i++) {         
    alert(testArray[i]);
}
</script>