Reputation: 2392
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,
Upvotes: 1
Views: 1726
Reputation: 13997
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
Upvotes: 3
Reputation: 622
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>
Upvotes: 2
Reputation: 2878
<div ng-repeat="item in array| orderBy:'data.length'>
here orderBy
takes property of data
Upvotes: 2
Reputation: 68933
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>
Upvotes: 1
Reputation: 2944
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>
Upvotes: 2