Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last record in an array in AngularJS

I have an array of objects ObjectsArr= [Object1 , Object2,Object3, Object4] I want to show in my view the last object, how to do that in angularjs?

like image 416
Besa Avatar asked Feb 26 '15 11:02

Besa


People also ask

How do I get the last record of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!

How do I find the last index?

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .


3 Answers

ObjectsArr[ObjectsArr.length - 1] -- this will give you the last element in the array.
To display it in view:
{{ObjectsArr[ObjectsArr.length - 1]}}

This will work even when the array has zero entries.

like image 96
Vinay K Avatar answered Sep 17 '22 17:09

Vinay K


You can use ng-if directive and check if element is last by:

ng-if="$last"

please see demo below

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

app.controller('homeCtrl', function ($scope) {

$scope.data = [1,2,3]
   

});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body >
  <div ng-app="app">
    <div ng-controller="homeCtrl">
<ul>
      <li ng-repeat="item in data" ng-if="$last">{{item}}</li>
</ul>
    </div>
    </div>
</body>
</html>
like image 38
sylwester Avatar answered Sep 20 '22 17:09

sylwester


For working with Arrays I recommend Lodash or Underscore. It will save you a lot of time in the future.

Both have last method:

_.last([1, 2, 3]); //Will return 3

See the links for API and installation.

As for viewing the result in the view, you can assign a scope variable in the relevant controller for the result and show it.

Controller:

$scope.lastItem = _.last(array);

View:

{{lastItem}}
like image 42
Or Guz Avatar answered Sep 20 '22 17:09

Or Guz