Blu Blu - 5 months ago 14
AngularJS Question

Sort subarrays in array with AngularJS

If I have a dataset that contains an array of objects, with each object having an array inside of them, how can I sort the subarrays by their properties? For example, here is some sample music data, it has 2 albums with tracks within them:

albums: [
{
type: "album",
name: "Brothers",
tracks: [
{
type: "track",
name: "Everlasting Light"
},
{
type: "track",
name: "Next Girl"
},
{
type: "track",
name: "Tighten Up"
}
]
},
{
type: "album",
name: "Listen",
tracks: [
{
type: "track",
name: "Around Town"
},
{
type: "track",
name: "Forgive & Forget"
}
]
}
]


The result would look like this:

- Around Town
- Everlasting Light
- Forgive & Forget
- Next Girl
- Tighten Up


Is there any way I can use an
ng-repeat
to create an alphabetically sorted list of music tracks?

I'd imagine it working something like below, but I tried with no success.

<p ng-repeat="track in albums.tracks">{{track.name}}</p>

Answer

Since you need only the tracks of albums, you should merge all the tracks in a single array and then just sort it alphabetically. Here's is a snippet working:

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

app.controller('mainCtrl', function($scope) {
  $scope.albums = [
    {  
      "type":"album",
      "name":"Brothers",
      "tracks":[  
         {  
            "type":"track",
            "name":"Everlasting Light"
         },
         {  
            "type":"track",
            "name":"Next Girl"
         },
         {  
            "type":"track",
            "name":"Tighten Up"
         }
      ]
   },
   {  
      "type":"album",
      "name":"Listen",
      "tracks":[  
         {  
            "type":"track",
            "name":"Around Town"
         },
         {  
            "type":"track",
            "name":"Forgive & Forget"
         }
      ]
   }
];
  
  $scope.tracks = [];
  angular.forEach($scope.albums, function(value) {
    $scope.tracks = $scope.tracks.concat(value.tracks);
  });
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js">
</script>
</head>

<body ng-controller="mainCtrl">
  <div ng-repeat="track in tracks | orderBy:'name'">
    <span ng-bind="track.name"></span>
  </div>
</body>
</html>