AngularJS: Sorting an Array of Objects in Descending Order

Solution 1:
To order in ascending or descending order, you can use the + or – prefix on the orderBy parameter.
For example, you can find more information at: http://www.w3schools.com/angular/ng_filter_orderby.asp
If you want to console.log it, simply add the name as a parameter in quotations.
Solution 2:
Instead of passing the second parameter as a property name, assign the filtered result to the desired scope variable wherever you need it.
Question:
I am using to list off items from an array of objects.


Question:

I’m trying to sort a basic array of objects in javascript using
$filter('orderBy')
, but for some reason, it’s not functioning correctly. I’ve even attempted it on jsFiddle.

Here is the code

var app = angular.module('myApp', []);
app.controller('myController', function($scope, $filter){
    var person = [{
  name : "Saras"
  },
  {
  name : "Arya"
  }];
  $filter('orderBy')(person, 'name');
  console.log(person);
});

I’m having trouble figuring out why this isn’t working. Any assistance would be greatly appreciated, preferably in JS rather than HTML.


Solution 1:

The orderBy parameter can be prefixed with either + or – to specify ascending (+) or descending (-) order.

example:

  • {{x.name + ", " + x.city}}
  • For additional information, please visit the following website: http://www.w3schools.com/angular/ng_filter_orderby.asp.

    To display it using console.log, simply include the name as a parameter within quotation marks.

    $filter('orderBy')(person, 'name');
    


    Solution 2:


    Ensure that the second parameter is set as the property name, referred to as
    name
    , and then assign the filtered result to the desired scope variable at the desired location. This way, no filtering will be required on the UI, as indicated by
    ng-repeat
    .

    $scope.person = $filter('orderBy')(person, 'name');
    
    {{p.name}}

    The Fiddle was forked at this location.


    If you wish to display it, you can store that property in a scope variable or alternatively apply this straightforward filtering on the client side when showing the records.

    {{p.name}}


    Demo here


    Solution 3:

    Example:

    
        {{friend.age}}
        {{friend.name}}
    
    

    Before your expression, employ the ‘-‘ symbol.


    Solution 4:


    $scope.person = $filter('orderBy')($scope.person , 'name', true);

    For descending order, the statement holds true, whereas for ascending order, it is false.

    Frequently Asked Questions