Array: var ranges = ["3-5", "1-4", "0-9", "10-10"];
I tried the following function:
ranges.sort();
// Output: 0-9,1-4,10-10,3-5
// Desired output: 0-9,1-4,3-5,10-10
Any idea how I can get to desired output?
If you want to sort by the first number, the approach is:
var desire = ranges.sort(function(a,b){return parseInt(a)-parseInt(b)});
Explanation: parseInt(a)
just removes everything after the non-number, i.e. -
and returns the number.
If you also want to make it sort by the first number properly if you have ranges starting with the same numbers (i.e. 3-5
and 3-7
):
var desire = ranges.sort(function(a,b){
return (c=parseInt(a)-parseInt(b))?c:a.split('-')[1]-b.split('-')[1]
});
Explanation: works as the first one until the first numbers are equal; then it checks for the second numbers (thanks Michael Geary for idea!)
If you want to sort by the result of equation, go for
var desire = ranges.sort(function(a,b){return eval(a)-eval(b)});
Explanation: eval(a)
just evaluates the expression and passes the result.
Also, as mentioned by h2ooooooo, you can specify the radix to avoid unpredictable behavior (i.e. parseInt(a, 10)
).
Here's one more:
var ranges = ["3-5", "1-4", "0-9", "10-10"];
ranges.sort(function(a, b) {
return a.split('-')[0] - b.split('-')[0];
});
console.log(ranges);
Output:
["0-9", "1-4", "3-5", "10-10"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With