基于Angular JS中对象数组中的数组长度进行排序

时间:2017-03-14 09:37:51

标签: javascript angularjs arrays sorting

考虑以下示例,

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

在视图中,我需要根据每个对象中data数组的长度按升序对对象进行排序。

在上面的例子中,roy,raj,ron。

我总是可以遍历数组,查找长度并对其进行排序,但是想知道是否有办法使用 Angular的OrderBy过滤器(视图或控制器)对其进行排序。

谢谢,

5 个答案:

答案 0 :(得分:2)

是的,你可以使用棱角分明的OrderBy filter

在视图中:

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

或在控制器中:

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

请参阅this jsfiddle

答案 1 :(得分:2)

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

此处orderBy具有data

的属性

答案 2 :(得分:2)

我们可以使用orderby子句

升序

DOT:

对于降序,我们需要使用&#39; - &#39;标志(单引号内)

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

答案 3 :(得分:1)

试试这个

  <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>

答案 4 :(得分:1)

尝试以下方法:

&#13;
&#13;
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);
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myController'>
</div>
&#13;
&#13;
&#13;