Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 946
Saras Arya Avatar asked Jul 22 '16 20:07

Saras Arya


People also ask

How to display data in descending order in Angular?

The "+" operator is used to order the data in ascending order and thde "-" operator is used to order the data in descending order.

How to use orderBy in AngularJS?

Parameter Values String: If the array is an array of objects, you can sort the array by the value of one of the object properties. See the examples below. Function: You can create a function to organize the sorting. Array: Use an array if you need more than one object property to determine the sorting order.

How do you sort an array in ascending order in angular 6?

display=this. addition. sort(); will sort the array in ascending order, to sort in descending order you need to pass a comparator function.


1 Answers

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');
like image 130
Aleksandar Đokić Avatar answered Oct 16 '22 07:10

Aleksandar Đokić