Andref
Andref

Reputation: 205

How to sort array of strings based on a contained number?

I have an array with strings like this:

"1115.49|Onroll|Paiporta|/v2/networks/onroll-paiporta"
"1767.92|Göteborg|Göteborg|/v2/networks/goeteborg"
"190.4|ARbike|Arezzo|/v2/networks/arbike"
"201.36|JesinBici|Jesi|/v2/networks/jesinbici"
"403.59|Venezia|Venezia|/v2/networks/venezia"
"395.07|Mantova|Mantova|/v2/networks/mantova"

the first value is a distance, I would like to sort the array based on that distance, how can I do?

Everything I've tried does not work, I would that 1000 come after 200 not before!

thanks!

Upvotes: 0

Views: 49

Answers (2)

Ben
Ben

Reputation: 1143

You can do something like this:

yourArray.sort(function (a, b) {
    var aNum = +a.substring(0, a.indexOf('|'));
    var bNum = +b.substring(0, b.indexOf('|'));
    if (aNum > bNum) return 1;
    if (aNum < bNum) return -1;
    return 0;
});

which will return an array in the ascending order you wanted.

Upvotes: 2

Tesseract
Tesseract

Reputation: 8139

If you add a sortBy function to Array.prototype you can do things like that more easily.

Array.prototype.sortBy = function(f) {
  this.sort(function(a, b) {
    a = f(a); b = f(b);
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
  });
}

and then you can write

array.sortBy(function(s) { return +s.split("|")[0]; });

Upvotes: 0

Related Questions