如何排序由3个点组成的字符串数字?

时间:2018-01-12 15:37:53

标签: javascript angularjs ng-options angularjs-ng-options

我有一个数组,其中包含3个点,例如&#34; 1.452&#34;,&#34; 11.3.2&#34;,&#34; 12&#34;。< / p>

例如,如果我对此数组进行排序

$scope.myArray=["11","14.2","9.2.1","5.6.3","0.9","6.7.2","2","1"];

我希望看到这样的数组

0.9,

1,

2,

5.6.3,

6.7.2

9.2.1,

11,

14.2

我想按降序排序这些值。我怎么能用AngularJS做到这一点?

提前谢谢。

2 个答案:

答案 0 :(得分:1)

它不漂亮,但我认为它有效:

var myArray = ["11", "14.2", "9.2.1", "5.6.3", "0.9", "6.7.2", "2", "1"];

function compare(a, b) {
  let aa = a.split(".");
  let bb = b.split(".");
  for (let i = 0; i < aa.length; i++) {
    if (parseInt(aa[i]) > parseInt(bb[i])) {
      return 1;
    } else if (parseInt(aa[i]) < parseInt(bb[i])) {
      return -1;
    }
  }
  return -1;
}

myArray = myArray.sort(function(a, b) {
  return compare(a, b)
})

console.log(myArray);

答案 1 :(得分:0)

所以你需要的是为Array.prototype.sort()函数编写自定义比较器。让我们看一下下面的例子(我将在评论中尝试解释)

&#13;
&#13;
const compareValues = (a, b) => {
  // for each element which we compare we need to split it using '.' to get comparable integers
  const aNumbers = a.split('.');
  const bNumbers = b.split('.');

  // then we start a look over the received arrays
  for (let i = 0; i < aNumbers.length || i < bNumbers.length; i++) {
  
    // here we take a current element. If we doesn't exist we consider it as 0
    let currentA = parseInt(aNumbers[i]) || 0;
    let currentB = parseInt(bNumbers[i]) || 0;
    
    
    if (currentA === currentB) {
    
      // if the numbers are equal, we go to the next pair of items
      continue;
      
    } else {
    
      // otherwise we return the difference between them, which says to sort() function which one is bigger
      return currentA - currentB;
    }
  }
  
  // if nothing was returned from the above for statement all numbers are equal
  return 0;
};

// here's the array, that you want to sort
const arr = ["11","14.2","9.2.1","5.6.3","0.9","6.7.2","2","1"];

// and just call the sort function with our comparator.
const sortedArr = arr.sort(compareValues);
&#13;
&#13;
&#13;