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,
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 asked Mar 14, 2017 at 9:37 Shrujan ShettyShrujan Shetty 2,4123 gold badges28 silver badges44 bronze badges5 Answers
Reset to default 3Yes 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
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./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>
<div ng-repeat="item in array| orderBy:'data.length'>
here orderBy
takes property of data
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>
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./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myController'>
</div>