Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-orderby

AngularJS: OrderBy Descending (null entries)


I'm using Angular JS and Google Places API to build an web app.

I have an ng-repeat which is currently being ordered by "rating" descending(orderBy:'-rating'). So it will list x places from the Google Places API JSON file in the descending order based on the rating.

HOWEVER, items/places that don't have a rating are classed as null and these entries are shown at the top of my ng-repeat feed. These should go to the bottom of the feed as they don't have a rating?

So an example of how i'd like this it to look is:

<ng-repeat orderBy:'-rating'>
  <place rating="5"/>
  <place rating="4.2"/>
  <place rating="2.8"/>
  <place rating="null"/>
  <place rating="null"/>
</ng-repeat>

What's the best way of going about this?


Solution

  • To sort with null or undefined value using orderBy filter. use [] notation orderBy:[ '!rating', '-rating', ].

    That will show null or undefined value at the bottom.

    like:

     <li ng-repeat="option in options | orderBy:[ '!rating', '-rating', ]">{{option.name}}</li>
    

    If you want only null values to go to the bottom you can use:
    orderBy: [ 'rating === null', '-rating' ]
    For all falsy values except 0 you can do:
    orderBy: [ 'rating !== 0 && !rating', '-rating' ]