Reputation: 515
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?
Upvotes: 19
Views: 53193
Reputation: 1
let arr = [6, 4, 9, 5, 56, 7];
let selectedNumber = 9;
// Find the index of the selected number
let index = arr.indexOf(selectedNumber);
if (index !== -1) {
// Get previous and next values
let previousValue = index > 0 ?
arr[index - 1] : undefined; // If it
exists
let nextValue = index < arr.length - 1 ?
arr[index + 1] : undefined; // If it
console.log(`Previous: ${previousValue},
Next: ${nextValue}`);
} else {
console.log("Selected number not
found.");
}
Upvotes: 0
Reputation: 15772
New way in ES6 ObjectsArr.at(-1)
Check usage and compatibility on MDN/Array/at
Upvotes: 0
Reputation: 5572
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.
Upvotes: 34
Reputation: 1
you can use reverse!
count = [0,1,2,3]
count.reverse()
//[3,2,1,0]
count[0];
// 3
Upvotes: -1
Reputation: 16498
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>
Upvotes: 19
Reputation: 1018
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}}
Upvotes: 13