1

We have a bunch of SomeItems which have a field someId which is in the format (simplified / replaced with dummies): abc.def1.<someNumber> I have an array of SomeItems and have been sorting it like this:

let rows = someItems.sort((lhs, rhs) => lhs.someId > rhs.someId)

This pretty much just sorts it alphabetically, so this means that the order comes out a little weird:

abc.def1.1
abc.def1.1234
abc.def1.1235
abc.def1.2
abc.def1.234

I instead want it to be numerically sorted - like 1, 2, 234, 1234, etc.

What's a clean way to do this?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
CustardBun
  • 3,457
  • 8
  • 39
  • 65
  • 1
    Just filter out the parts you don't want (with regex or something else) when comparing in the comparator function. – tyteen4a03 Nov 08 '17 at 18:40
  • Also note that the comparator should return a number, not a boolean. – CRice Nov 08 '17 at 18:41
  • Btw, notice that `(lhs, rhs) => lhs.someId > rhs.someId` [is not a working comparison function for `sort`](https://stackoverflow.com/q/24080785/1048572) – Bergi Nov 08 '17 at 18:44

1 Answers1

2

You could use String#localeCompare with options.

var array = ['abc.def1.1', 'abc.def1.1234', 'abc.def1.1235', 'abc.def1.2', 'abc.def1.234'];

array.sort(function (a,b) {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392