S.Yadav
S.Yadav

Reputation: 4509

How to retrieve last element id of array in Angular 2

I am trying to get id of last element of my array.

This is how I am fetching last element of my array

let last = this.Array[this.Array.length-1];
console.log(last);

Here is the console of last element of array-

Object {id: 48, title: "I'm used to this"}
 title: "I'm used to this"
 id:  48
__proto__:  Object

Here is the list on which I have looked already-

How to retrieve the clicked ElementId in angularjs?
How to get the object's id?
how to get the id name in html for any object and many more but I could not.

I just wanted to access id : 48, can any one help me to do so.
Thanks In Advance.

Upvotes: 5

Views: 48184

Answers (2)

Duannx
Duannx

Reputation: 8746

Just do that:

let last:any = this.Array[this.Array.length-1];
console.log(last.id);

Upvotes: 11

anoop
anoop

Reputation: 3822

You can do this.Array.slice(-1)[0].id, and with slice your original array is not changed too.

DEMO :

var array = [{
  id: 43,
  title: "I'm used to this"
},{
  id: 44,
  title: "I'm used to this"
},{
  id: 45,
  title: "I'm used to this"
},{
  id: 46,
  title: "I'm used to this"
},{
  id: 47,
  title: "I'm used to this"
},{
  id: 48,
  title: "I'm used to this"
}]

console.log('last id : ' + this.array.slice(-1)[0].id)

Update:

As your Array item is type of Object, So first convert it to some real class\interface type, Something like:

export  interface arrayItem{
    id?: number;
    title?: string;
}

then define your array type, like :

your Array like

this.Array : Array<arrayItem> = [ {
  id: 48,
  title: "I'm used to this"
  },
  //your other array items
]

Upvotes: 6

Related Questions