Javascript Sort Array删除特殊的Array拆分字符

时间:2014-02-12 16:49:43

标签: javascript arrays sorting

我使用双逗号(,,)作为我的数组拆分分隔符。所以,当我去分割我的数组时,我使用:

    var flt = localStorage.getItem('flt');
    var fltArray = new Array();
    var fltArray = flt.split(",,");

当我对数组进行排序时,我的排序代码会删除每个元素末尾的逗号。因此,所有数组元素之间的分割在最初时变为“,”,“,”

我正在使用以下代码对数组进行排序。

fltOfferSellEconArray.sort(function(x,y){
         var xp = x.substr(0,4);
         var yp = y.substr(0,4);
         return xp == yp ? 0 : xp > yp ? -1 : 1;
   });

有没有办法在每个元素的末尾添加一个逗号,而不必再次遍历数组?

这是排序前我的数组.....

["0000999X12623220000009999999999,","0300199X1392215130873ySP3sBJLTe,","0301199X1392215191700ySP3sBJLTe,","0302199X1392215252490ySP3sBJLTe,","0303199X13922153062748VplSv6axJ,","0400199X13922155681178VplSv6axJ," ,"0375199X1392215732050ySP3sBJLTe,"]

这是排序后我需要的样子。 (注意......它只是将以“0400”开头的元素移动到最后一个元素.....

["0000999X12623220000009999999999,","0300199X1392215130873ySP3sBJLTe,","0301199X1392215191700ySP3sBJLTe,","0302199X1392215252490ySP3sBJLTe,","0303199X13922153062748VplSv6axJ,","0375199X1392215732050ySP3sBJLTe,","0400199X13922155681178VplSv6axJ,"]

1 个答案:

答案 0 :(得分:1)

这似乎对我很好:

> a = ["0000999X12623220000009999999999,","0300199X1392215130873ySP3sBJLTe,","0301199X1392215191700ySP3sBJLTe,","0302199X1392215252490ySP3sBJLTe,","0303199X13922153062748VplSv6axJ,","0400199X13922155681178VplSv6axJ," ,"0375199X1392215732050ySP3sBJLTe,"]
> a.sort(function(x,y){
     var xp = x.substr(0,4);
     var yp = y.substr(0,4);
     return xp == yp ? 0 : xp > yp ? -1 : 1;
  });
> a
["0400199X13922155681178VplSv6axJ,", "0375199X1392215732050ySP3sBJLTe,", "0303199X13922153062748VplSv6axJ,", "0302199X1392215252490ySP3sBJLTe,", "0301199X1392215191700ySP3sBJLTe,", "0300199X1392215130873ySP3sBJLTe,", "0000999X12623220000009999999999,"]

究竟什么不适合你?