Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Consider the following example,

var arrayOfObject = [
{name: 'ron', data: [1,3,5]},
{name: 'raj', data: [2,3]},
{name: 'roy', data: [1]}
]

In the view, I need to sort the objects in ascending order based on the length of data array in each objects.

In the above example roy, raj, ron.

I could always loop through the array, find the length and sort it, But was wondering if there was a way to sort it using Angular's OrderBy Filter (view or controller).

Thanks,

share|improve this question
up vote 2 down vote accepted

Yes your can use angular's OrderBy filter.

In view:

<div ng-repeat="item in arrayOfObject | orderBy:'-data.length'">

Or in controller:

var ordered = $filter("orderBy")(arrayOfObject, "-data.length");

See this jsfiddle

share|improve this answer
<div ng-repeat="item in array| orderBy:'data.length'>

here orderBy takes property of data

share|improve this answer

Try this

  <div ng-repeat="item in arrayOfObject | orderBy:'data.length'">
    {{item.name}}:{{item.data.length}}
  </div>

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
  $scope.arrayOfObject = [{
      name: 'ron',
      data: [1, 3, 5]
    },
    {
      name: 'raj',
      data: [2, 3]
    },
    {
      name: 'roy',
      data: [1]
    }
  ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
ASEC:
  <div ng-repeat="item in arrayOfObject | orderBy:'data.length'">
    {{item.name}}:{{item.data.length}}
  </div>
<br/>
DESC:
  <div ng-repeat="item in arrayOfObject | orderBy:-'data.length'">
    {{item.name}}:{{item.data.length}}
  </div>
</div>

share|improve this answer

Try the following:

var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', '$filter', function($scope, $filter){

var arrayOfObject = [
  {name: 'ron', data: [1,3,5]},
  {name: 'raj', data: [2,3]},
  {name: 'roy', data: [1]}
]
$scope.arrayOfObject = $filter("orderBy")(arrayOfObject, 'data.length');
  console.log($scope.arrayOfObject);
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myController'>
</div>

share|improve this answer

We can use orderby clause

For Ascending

<div ng-repeat="item in arrayOfObject | orderBy:'data.length'">
    {{item.name}}:{{item.data.length}}
  </div>

For Descending order we need to use '-' sign (inside single quotes)

<div ng-repeat="item in arrayOfObject | orderBy:'-data.length'">
    {{item.name}}:{{item.data.length}}
  </div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.