Reputation: 2102
If I have an array like:
["23", "765", "sfasf", "2.3E-3", "2.3cE-3"]
How can I order it so numbers(decimals, floats or scientific notation) are ordered ascending and after those strings that aren't numbers(for example "sfasf" or "2.3cE-3")?
Expected order of the example array:
["2.3E-3", "23", "765", "2.3cE-3", "sfasf"]
The order of the strings that can't be converted to numbers doesn't matter, they just must be at the end.
Solution from answer:
$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);
}
Upvotes: 3
Views: 4557
Reputation: 382504
You can do
var arr = arr.sort(function(a,b){ return ((+b==b) && (+a!=a)) || (a-b) })
The idea is to make two comparisons:
(+b==b) && (+a!=a)
: return true
(converted to 1
) if b
is a number and a
isn'ta-b
: then compare the numbers if the first comparaison isn't enoughMore in depth : +a
converts a
to a number. It is equal (for ==
, not for ===
) to a
when and only when +a
is a number (remember, NaN
isn't equal to NaN
).
Upvotes: 5
Reputation: 802
sort
function accept a function comparaison as parameter.
Define your
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);
}
}
}
and use it like
yourArray.sort(compareFct);
Upvotes: 0