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 the desired result?

+4
source share
4 answers

If you want to sort by first number, the approach is:

var desire = ranges.sort(function(a,b){return parseInt(a)-parseInt(b)});

Explanation: it parseInt(a)simply deletes everything after the non-number, i.e. -and returns the number.

If you also want to make it sorted by the first number correctly, if you have ranges starting with the same numbers (i.e. 3-5and 3-7):

var desire = ranges.sort(function(a,b){
   return (c=parseInt(a)-parseInt(b))?c:a.split('-')[1]-b.split('-')[1]
});

Explanation: works like the first, until the first numbers are equal; then he checks for a second number (thanks Michael Geary for the idea!)

,

var desire = ranges.sort(function(a,b){return eval(a)-eval(b)});

: eval(a) .

, h2ooooooo, , (.. parseInt(a, 10)).

+4

, , - , , , :

[ "3-5", "1-5", "1-4", "10-9", "0-9", "10-10" ];

, :

[ "0-9", "1-4", "1-5", "3-5", "10-9", "10-10" ]

, , -, . , , , , .

function sortRanges( range ) {
    return ranges.sort( function( a, b ) {
        var aSplit = a.split( '-' ), aStart = aSplit[0], aEnd = aSplit[1];
        var bSplit = b.split( '-' ), bStart = bSplit[0], bEnd = bSplit[1];
        return aStart - bStart ? aStart - bStart : aEnd - bEnd;
    });
}

var ranges = [ "3-5", "1-5", "1-4", "10-9", "0-9", "10-10" ];
console.log( sortRanges( ranges ) );

.

: sort() , . , , .

, , , . , , , .

- // . ( , .) , . parseInt() - .

+2

Another boring answer:

var r = /^(\d+)-(\d+)$/;
var ranges = ['3-5', '1-4', '0-9', '10-10'];
ranges.sort(function (a, b) {
  a = a.match(r);
  b = b.match(r);
  a = Math.abs(a[1] - a[2]);
  b = Math.abs(b[1] - b[2]);
  return b - a;
});
document.write(ranges);
Run codeHide result
+2
source

Here's another one:

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"]
+2
source

Source: https://habr.com/ru/post/1621518/


All Articles