How to get the index of the last element in a 2D array in Angular.js using ng-repeat

Posted by


In AngularJS, ng-repeat is a directive that is used to loop through a collection of items and iterate over them in the HTML template. When dealing with a 2D array in ng-repeat, you might encounter a situation where you need to get the index of the last element in the array.

To achieve this, you can use a combination of ng-repeat, $index, and a custom filter function. Here’s a step-by-step tutorial on how to get the index of the last element in a 2D array in ng-repeat:

  1. Define your 2D array in the controller:
    First, define your 2D array in the AngularJS controller. For example, you can define a 2D array of numbers like this:

    $scope.myArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
    ];
  2. Use ng-repeat to loop through the 2D array:
    Next, use ng-repeat to loop through the 2D array in the HTML template. You can nest ng-repeat directives to iterate over both the outer and inner arrays. For example:

    <div ng-repeat="row in myArray">
    <div ng-repeat="item in row">
    <p>{{item}}</p>
    </div>
    </div>
  3. Create a custom filter function:
    To get the index of the last element in the 2D array, you can create a custom filter function in the controller. This function will iterate over the array and return the index of the last element. Here’s an example of a custom filter function:

    $scope.getLastIndex = function(array) {
    return array.length - 1;
    };
  4. Use the custom filter function in ng-repeat:
    Finally, use the custom filter function in ng-repeat to get the index of the last element in the 2D array. Pass the current row or column to the filter function and use the $last variable provided by ng-repeat to check if it is the last element. For example:

    <div ng-repeat="row in myArray">
    <div ng-repeat="item in row">
    <p>{{item}}</p>
    <p ng-if="$last">{{getLastIndex(row)}}</p>
    </div>
    </div>

By following these steps, you can easily get the index of the last element in a 2D array when using ng-repeat in AngularJS. This technique can be useful when you need to perform specific actions or calculations based on the index of the last element in the array.