1

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,

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

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

here orderBy takes property of data

Comments

2

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>

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.