19

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?

6 Answers 6

34

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.

Sign up to request clarification or add additional context in comments.

7 Comments

@sylwester's answer with ng-if="$last" below is WAY better.
What if the length is 0? O - 1 = -1 oh dear.
@senthe I strongly disagree. What if the array has a 1000 entries? What if they are going to have this value in a table of 50 rows? You're going to look over 50,000 entries for 50 results? Terrible performance. To fix Paul Rooney comment we'll have to use a ternary in the angular template ((condition) && (answer if true) || (answer if false)) Which would be {{((ObjectsArr.length > 0) && (ObjectsArr[ObjectsArr.length - 1]) || (0) }} Blah. Looks like spaghetti code! If possible have your data return the result you want. Other wise consider writing a function to do this for you.
@MGot90 What are your assumptions about Angular's $last performance based on?
@Senthe Please check the below plnkr links for the performance comparison plnkr.co/edit/5RxESflqbKlHAwafe125?p=preview and plnkr.co/edit/ItuNXqQYInWYYygmpQqD?p=preview
|
19

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>

8 Comments

This works but the answer of Vinay works as well and he responded first. Thank you . I will up vote your answer
@Besa: you don't have to mark a response as 'best answer' just because it arrived first. You should instead mark whichever response helped you the most. In this case, that may be the same answer anyway. :-)
This is definitely the best answer here, not sure why another got accepted.
@Senthe we should not agree an answer just because its cleaner. We should consider the performance and best practices. only to render the last record in a list we should not be rendering the complete list. In this case ng-if directive will be compiled n number of times (where n is the length of the list)
I strongly disagree with this answer. What if the array has a 1000 entries? What if they are going to have this value in a table of 50 rows? You're going to look over 50,000 entries for 50 results? Terrible performance. To fix selected answer use a ternary in the angular template ((condition) && (answer if true) || (answer if false)) Which would be {{((ObjectsArr.length > 0) && (ObjectsArr[ObjectsArr.length - 1]) || (0) }} Blah. Looks like spaghetti code! If possible have your data return the result you want. Other wise consider writing a function to do this for you.
|
13

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}}

2 Comments

Underscorejs is a verty nice library, but the OP requested an answer for plain javascript.
He asked how to do that in angularjs, Ofcourse he doesn't have to use those libraries but I think this tip might help him a lot for future arrays manipulations.
0

New way in ES6 ObjectsArr.at(-1)

Check usage and compatibility on MDN/Array/at

Comments

0
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.");
}

1 Comment

Please explain how this addresses the issue. What have you changed? Code-only answers are not good answers
-1

you can use reverse!

count = [0,1,2,3]

count.reverse() 
//[3,2,1,0]

count[0];   
// 3

1 Comment

Reversing a list to get the last element is an unnecessary O(log n) operation. If you just get the last element that's a constant time operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.