Home > Software design >  how to find the last element from array?
how to find the last element from array?

Time:11-22

I have array something like

comments:[{'no':'d1', 'comment':'XYZ},{'no':'f3', 'comment':'ABC'}]

I trying access the last element of array, tried with: <td>{{cus.comments}}</td> that showing [object object] I understood as array I need to loop but I am willing too as I just want to show the last obj's comment.

Saw I also tried with

cus.comments[-1].comment cus.comments.at(-1).comment cus.comments.slice(-1).comment

in table value in comment column should come the last comment from comments.

'ABC'

CodePudding user response:

You can use the Array.prototype.at method

Like this:

const users = [{'name':'user1', 'comment':'XYZ'},{'name':'user2', 'comment':'ABC'}];

const lastUserComment = users.at(-1).comment;

console.log(lastUserComment)

CodePudding user response:

You can use:

cus.comments.slice(-1).pop().comment;

or:

cus.comments.slice(-1)[0].comment;

have a look at this link

  • Related