简体   繁体   中英

Sorting with Angularjs OrderBy in special cases

I have some data which I'm attempting to sort in a table using Angular's orderBy filter. Here's the data I'm attempting to sort.

[
  {
    "name":"John Doe",
    "room":"1M-103",
  },
  {
    "name":"Joe Schmoe",
    "room":"12M-353",
  },
  {
    "name":"Bob Guy",
    "room":"13M-546",
  },
  {
    "name":"Another Person",
    "room":"12M-403",
  },
  {
    "name":"Fred No-name",
    "room":"3M-204",
  },
[

So sorting by name works just fine. Sorting by room, however, is another issue. I'm sorting it the exact same way. Here's what I would like it to look like after sorting:

1M-103
3M-204
12M-353
12M-403
13M-546

How it actually looks after the sorting is this:

12M-353
12M-403
13M-546
1M-103
3M-204

Anyone able to help? I know why it's sorting like that, because it's going digit by digit and sorting it correctly, but is there some way that someone has found to get some slightly better sorting?

You can create a custom sorter to do that.

<li ng-repeat="item in items | orderBy:mySorter">{{item}}</li>

$scope.mySorter = function (item) {
    return Number(item.room.split('-')[0].replace('M', ''));
}

I also created a demo for you.

Updated

You can also use Regex:

$scope.mySorter = function (item) {
    return Number(item.room.replace(/[^\d]/g, ''));
}

Demo

Actually sza's answer doesn't quite work, since it only takes into account the numbers before the letter 'M'. So everything that starts with 12M would be read as '12' and considered equal. All the 12M's would come after 11M's and before 13M's, but would then be displayed in a random order among other 12M's.

I worked up this code:

<li ng-repeat="item in items | orderBy:mySorter">{{item}}</li>

$scope.mySorter = function (item) {
    return Number(item.residenceRoom.replace('M', '.').replace('-', ''));
}

It creates a decimal number based on the number before the M dot the number after the M. So 12M-353 would be '12.353' and 12M-403 would be '12.403' so they would be sorted correctly.

The only problem I see is if the room numbers aren't always 3 digits. For example a hypothetical room 1M-2 would be sorted as '1.2' while room 1M-103 would be '1.103' so a room 2 would be sorted after room 103. But you could fix this pretty easily by formatting all your rooms with 3 digits, eg. room 1M-002.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM