How to orderBy a array of objects in descending order in angularjs?

Saras Arya picture Saras Arya · Jul 22, 2016 · Viewed 44k times · Source

I have a very simple array of objects and I want to sort it using $filter('orderBy') in javascript. Somehow it doesn't seem to work. 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 don't understand why I can't get this to work? Help is appreciated. And the solution should be in JS not in HTML.

Answer

Aleksandar Đokić picture Aleksandar Đokić · Jul 22, 2016

Adding + or - prefix on orderBy parameter will order by + (ascending) or -(desc);

example:

<li ng-repeat="x in customers | orderBy : '-city'">
    {{x.name + ", " + x.city}}
</li>

more at : http://www.w3schools.com/angular/ng_filter_orderby.asp

Or if you want to console.log it then just add name as parameter in quotations :

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