Plemo Plemo - 4 months ago 22
AngularJS Question

Order integer values ascending in a multidimensional array inside a ng-repeat in angularjs

I want to create a Highscore table.

I have an multidimensional array which I display in my script through ng-repeat in a table. My array looks like this:

[["name1","name2","name3"],[1,2,1,],[12,24,4]]


My html code looks like this:

<tbody>
<tr ng-repeat="x in highscoreEntries track by $index">
<td>{{$index+1}}</td> <!--Showing the rank number-->
<td ng-repeat="y in x track by $index">{{y}}</td>
</tr>
</tbody>


I would like to order the values ascending, depending on the numbers in the inner array with angularjs. The Index changes have to be applied on all inner arrays: [0][x],[1][x],[2][x] should always be the same. The table should display the array like this:

[["name3","name1","name2"],[1,1,2],[4,12,24]]


I already have a workaround. I sort my array before I create the table, but I would like to know, if it is possible just with "|order by" or other functions where i dont have to alter my original array variable.

Answer

Try this sort method. its working. You should change index of the value from each array.

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

app.controller('MainCtrl', function($scope) {
  var arr  = [["name1","name2","name3"],[1,2,1],[12,24,4]];
  $scope.highscoreEntries = [];
  
   for(var i=0;i<arr.length;i++){
     $scope.highscoreEntries.push(sortA(arr[i]));
   }
   function sortA(arr){
 var element = arr[2];   // 2 is from index
    arr.splice(2, 1);    // 2 is from index
    arr.splice(0, 0, element);   // .splice(toindex,0,element)
    return arr;
   } 
});
  <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script>
    
<body ng-app="plunker" ng-controller="MainCtrl">
 <table>
    <tbody>
                <tr ng-repeat="x in highscoreEntries track by $index">
                    <td>{{$index+1}}</td> <!--Showing the rank number-->
                    <td ng-repeat="y in x track by $index">{{y}}</td>
                </tr>
            </tbody>
        </table>    
  </body>