2

I have an array of objects in Angular that I am trying to sort a very specific way and I can't figure it out.

Here's sample Javascript:

var app = angular.module('app', []);

function Ctrl($scope) {
  $scope.divisions = [      
      {'group':'d','sub':1}, 
      {'group':'a'}, 
      {'group':'z','sub':2},
      {'group':'g','sub':20},
      {'group':'g'},
      {'group':'r','sub':11}];
}

Here's sample HTML:

<div class="test" ng-controller="Ctrl">
  <div ng-repeat="division in divisions | orderBy:['sub','group']">{{division.group}}-{{division.sub}}</div>
<div>

Here's the fiddle: https://jsfiddle.net/r4nsyp2v/1/

And instead of it displaying like:

d-1
z-2
r-11
g-20
a-
g-

I want it to display like:

g-20
r-11
z-2
d-1
a-
g-

So I would want to display the 'sub' key from largest to smallest if it exists, with the undefined 'sub' keys after. And display the objects with undefined 'sub' keys alphabetically by group.

I haven't found the trick yet....any ideas?

JulieMarie
  • 400
  • 1
  • 6
  • 21
  • Try `orderBy:['-sub','group']` – zs2020 Apr 01 '15 at 18:59
  • I guess I could split the array into two different arrays (one with 'sub' defined and one without), sort them and then put them back together. It seems like there should be a cleaner way though. – JulieMarie Apr 01 '15 at 18:59
  • Use a filter after doing '-sub': http://stackoverflow.com/questions/18604374/angularjs-orderby-with-empty-field – MingShun Apr 01 '15 at 19:04

1 Answers1

3

You could create your custom order like this:

$scope.order = function(division) {
  return -(division.sub || 0);
}

And in the HTML

<div ng-repeat="division in divisions | orderBy:order">

See example https://jsfiddle.net/r4nsyp2v/2/

floribon
  • 19,175
  • 5
  • 54
  • 66