2015-05-29 46 views
1

如果我有這樣一個數組:的Javascript排序()排列

["23", "765", "sfasf", "2.3E-3", "2.3cE-3"] 

如何訂購它使數字(小數,漂浮或科學記數法)是有序的上升和那些AREN串後數字(例如「sfasf」或「2.3cE-3」)?

的示例性陣列的預期的順序:

["2.3E-3", "23", "765", "2.3cE-3", "sfasf"] 

不能被轉換爲數字無關緊要字符串的順序,他們只是必須是在末端。從答案

解決方案:

$scope.cleanAndOrder = function(dbo, fieldName) { 
    var textareaId = "textarea"+"_"+fieldName ; 
    var textarea= document.getElementById(textareaId); 

    //(+b && (+a!=a)) : return true (converted to 1) if b is a number and a isn't 
    //(a-b) : then compare the numbers if the first comparaison isn't enough 
    textarea.value = dbo.attributes[fieldName].sort(function(a,b){ return (+b && !+a) || (a-b) }).join("\n"); 
    var lines = textarea.value.split("\n"); 
    textarea.setAttribute('rows', lines.length +2); 
} 
+2

使用LO-劃線或下劃線:) –

+1

感謝你能指出特定功能的註釋,好嗎? –

+0

你想要一個特定的字符串順序嗎? –

回答

5

你可以做

var arr = arr.sort(function(a,b){ return ((+b==b) && (+a!=a)) || (a-b) }) 

的想法是讓兩個比較:

  • (+b==b) && (+a!=a):返回true(轉換爲1)如果b是一個數字,a不是
  • a-b:然後比較這些數字,如果第一comparaison不夠

更深入:+a轉換a爲數字。當且僅當+a是數字(記住,NaN不等於NaN)時,它等於(對於==,而不是for ===)到a

+0

可以請你爲你張貼的代碼添加一些解釋嗎? – Alex

+0

@Alex現在清楚了嗎? –

+0

可以請你去一點細節。不是一個下來的選民 – Alex

0

sort函數接受函數comparaison作爲參數。

定義您

function compareFct(a, b) { 
    if (isNaN(a)) { 
     if (isNaN(b)) { // a and b are strings 
      return a.localeCompare(b); 
     } else {   // a string and b number 
      return 1; // a > b 
     } 
    } else { 
     if (isNaN(b)) { // a number and b string 
      return -1; // a < b 
     } else {   // a and b are numbers 
      return parseFloat(a) - parseFloat(b); 
     } 
    } 
} 

,並使用它像

yourArray.sort(compareFct);