Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have nested array that i need to sort by age. Means if any female age largest of any male age then female goes first.

 data = {"people": 
   [{"male": [
     {"name": "Bob" ,"age": "32"}, 
     {"name":"Mike", "age":"22"}
    ]}, 
    {"male_two": [
     {"name": "Rob" ,"age": "12"}, 
     {"name":"Tom", "age":"2"}
    ]}, 
   {"female": [
     {"name":"Jessica", "age": "24"}, 
     {"name":"Ann", "age": "43"}
   ]}, ...
   ]} 

So in my case i need to return:

data = {"people": 
   [{"female": [
     {"name":"Jessica", "age": "24"}, 
     {"name":"Ann", "age": "43"}
    ]}, 
    {"male": [
     {"name": "Bob" ,"age": "32"}, 
     {"name":"Mike", "age":"22"}
    ]},
    {"male_two": [
     {"name": "Rob" ,"age": "12"}, 
     {"name":"Tom", "age":"26"}
    ]}, ...
    ]} 

Can i use angular $filter for?

share

1 Answer 1

You can write your own orderBy-function.

$filter('orderBy')(array, expression, reverse)

https://docs.angularjs.org/api/ng/filter/orderBy

function: Getter function. The result of this function will be sorted using the <, ===, > operator.

$scope.customOrder = function(gender) {
    var highestAge = 0;
    for(person in gender) {
        if(gender[person].age > highestAge) {
            highestAge = gender[person].age;
        }
    }
    return highestAge;
}

You can either use this in an ng-repeat attribute:

ng-repeat="g in people.gender| orderBy:customOrder"

Or with the $filter-Service ( https://docs.angularjs.org/api/ng/service/$filter ).

The code above is untested but i hope you get the point.

share

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .