god599
god599

Reputation: 13

ng-repeat sort complex objects having arrays inside it

I have a structure like this which needs to be sorted by Locations.Address.distance

{
    "Id": "123",
    "Type": "someType",          
    "Locations": [{
        "Address": {
            "Line1": "111 test dr",
            "City": "pope",
            "State": "AZ",
            "PostalCode": {
                "Part1": "87212"
            } 
        },
         "Distance": "0.7" }]  
},

{
    "Id": "456",
    "Type": "someType",          
    "Locations": [{
        "Address": {
            "Line1": "777 test dr",
            "City": "pope",
            "State": "AZ",
            "PostalCode": {
                "Part1": "87212"
            } 
        },
         "Distance": "0.1" }]  
}

Locations array will always have only 1 item. I want to sort such that the second object with id= 456 shows up as the first element, as it has distance = 0.1, which is lesser than that of the first element where distance = 0.7 . I tried something like this, but it doesn't work:

 sortedList =filter('orderBy')($scope.responseArray,'Locations.this[0].Distance'], false);

Upvotes: 1

Views: 47

Answers (2)

Jameel Moideen
Jameel Moideen

Reputation: 7931

By using filter you do like below

 var result=$filter('orderBy')(this.items, 'Locations[0].Distance')

https://stackblitz.com/edit/js-sort-complex-array?file=index.js

Another approach is to use javascript sort() method , which you can written your own logic to sort

var result = items.sort(function (a, b) {
  var distance1 = parseFloat(a.Locations[0].Distance); 
  var distance2 = parseFloat(b.Locations[0].Distance); 
  if (distance1 < distance2) {
    return -1;
  }
  if (distance1 > distance2) {
    return 1;
  }


  return 0;
});

Working demo

https://stackblitz.com/edit/angularjs-complex-filter?file=home/home.controller.js

Upvotes: 1

god599
god599

Reputation: 13

The trick was to refer to the first item inside of Locations array without using "this":

 sortedList = $filter('orderBy')($scope.pharmacyResponse, Name.LastName','Locations[0].Distance'], false);

Upvotes: 0

Related Questions