Imagine having this array:
var fees = [
'$0.9 + $0.1',
'$20 + $2',
'$0.7 + $0.4',
'$5 + $0.5',
'$0 + $0.01',
'$100 + $9',
'$1 + $1',
'$2 + $0.5'
];
How would I, with vanilla JavaScript, go about sorting these string values in numeric ascending order?
The desired output after sorting:
['$0 + $0.01', '$0.7 + $0.4', '$0.9 + $0.1', '$1 + $1', '$2 + $0.5', '$5 + $0.5', '$20 + $2', '$100 + $9']
I tried the following:
function mySort(a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
But that simply outputs:
["$0 + $0.01", "$0.7 + $0.4", "$0.9 + $.1", "$1 + $1", "$100 + $9", "$2 + $0.5", "$20 + $2", "$5 + $0.5"]`
Is this possible in a neat and logical way?
I don't wish to get the sum as it will yield unwanted results. Consider the example of "$0.9 + $0.1"
and "$0.7 + $0.4"
. "$0.9 + $0.1"
will be a lower value as the sum is 1
, but I would like to sort so that "$0.7 + $0.4"
is a lower value instead. So basically the wish is to sort on the first number ascending, and if the first number is the same between two values, then sort those on the second number