0

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

return +a.substring(0, a.indexOf('|')) - +b.substring(0, a.indexOf('|')) should be enough.
thanks! but I keep getting: Uncaught TypeError: undefined is not a function where am I wrong?
@Andref replace yourArray with your array.
There was a problem creating the array, now it works, thanks to all!
0

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]; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.