Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array in ascending order

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?

like image 835
arled Avatar asked Dec 25 '22 11:12

arled


2 Answers

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)).

like image 121
nicael Avatar answered Jan 08 '23 19:01

nicael


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"]
like image 23
Will Avatar answered Jan 08 '23 18:01

Will