2

I want to sort an array of addresses. Seems simple enough by using the .sort() method on my array.

But... Try looking here: https://jsfiddle.net/ytuzr918/

The .sort() method sorts perfectly alphabetically (at least I assume it does). However my addresses have numbers and even more letters after the numbers.

So is there a way to sort the array "right", probably by prototyping the sort method?

0

3 Answers 3

3

You can provide a comparison function to Array.prototype.sort().

Adapting the answer from here :

var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
    var aA = a.replace(reA, "");
    var bA = b.replace(reA, "");
    if(aA === bA) {
        var aN = parseInt(a.replace(reN, ""), 10);
        var bN = parseInt(b.replace(reN, ""), 10);
        return aN === bN ? 0 : aN > bN ? 1 : -1;
    } else {
        return aA > bA ? 1 : -1;
    }
}
console.log(addresses.sort(sortAlphanum));
2

Array sort method in javascript takes one optional argument which is a compare function. You can define this compare function as per your requirements.

arr.sort([compareFunction])

compareFunction(Optional). Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

See Mozilla Developer Network for more details.

0

This is pretty common sorting for the .sort() function. What you could do is pass the method your own custom comparison function so that it'll use that to determine sort order.

addresses.sort(function (a, b) {
  var val_a = Number.parseInt(a.replace('Nordmarksvej ', ''));
  var val_b = Number.parseInt(b.replace('Nordmarksvej ', ''));

  if (val_a === val_b) {
    return 0;
  }

  return val_a > val_b ? 1 : -1
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.