Linc Abela
Linc Abela

Reputation: 815

AngularJS: GroupBy then Sort

I have a collection and im grouping it using lodash.js groupBy before displaying in the UI using ng-repeat

    var list = [{id:1,categoryId:1,name:test1},
                {id:2,categoryId:2,name:test2},
                {id:3,categoryId:12,name:test12}]

    vm.myList= _.groupBy(list,function (j) { return j.categoryId; });

    console.debug(vm.myList) // this shows the correct ordering!!!

Now when im displaying it using ng-repeat it messes up the ordering

<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'categoryId'>
        {{ categoryId }}
</div>

this displays

1
12
2

how can I make it to display

1
2
12

I'm trying something like this but no luck

<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'parseInt(categoryId)'>
            {{ categoryId }}
    </div>

UPDATE! I found out that this is not an issue in Angular 1.4.x . Unfortunately, we are using old version Angular 1.3.x

Upvotes: 0

Views: 380

Answers (1)

Grundy
Grundy

Reputation: 13381

first, orderBy filter working only with arrays, so if you try pass object to it, would be returned passed object as is.

second, with ngRepeat

You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)

Version 1.4 removed the alphabetic sorting.

If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter

So for solving your issue just convert your groupped object to array, and sort it as you want.

Upvotes: 2

Related Questions