0

I have an array list and and I want only last record from the array list, how to get that?array list

I want message(i.e. Hey) from last record of this array.

here is my code:

let chats : any = [];

  items.forEach((item) =>
  {
    if(item.val().sent_by == loggedInUserKey && item.val().sent_to == UserKey)
    {
      chats.push({
        key              : item.key,
        sent_by          : item.val().sent_by,
        sent_to          : item.val().sent_to,
        message          : item.val().message,
        datetime         : item.val().datetime
      });
    }
    if(item.val().sent_to == loggedInUserKey && item.val().sent_by == UserKey)
    {
      chats.push({
        key              : item.key,
        sent_by          : item.val().sent_by,
        sent_to          : item.val().sent_to,
        message          : item.val().message,
        datetime         : item.val().datetime
      });
    }
  });
  this.chats = chats;
  var last = chats[chats.length - 1];
  console.log("last: ",last);
  console.log("Chats : ",this.chats);

Please help. Thanks in advance.

8
  • Please add code not image... Commented May 2, 2018 at 6:29
  • you want angular html template or just javascript code to access last record? Commented May 2, 2018 at 6:30
  • 1
    Duplicate of duplicate! Commented May 2, 2018 at 6:31
  • @NamanKheterpal just javascript Commented May 2, 2018 at 6:32
  • @Zich Tried it already Commented May 2, 2018 at 6:33

6 Answers 6

6

You could just use array.length-1 to find the last value. I'll include a code snippet demonstration below:

const myArrayList = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu'];

console.log(myArrayList[myArrayList.length - 1]);

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

Comments

3

Try this:

var lastMessage = chats[chats.length - 1].message;
console.log(lastMessage);

1 Comment

Thanks. worked it. :)
2

use array[array.length - 1]

Example:

var array = [1,2,3,4,5,6,7,8,9,10];

var lastVal = array[array.length - 1];

console.log(lastVal);

Comments

2

You could write something like this:

someArray[someArray.length - 1]

Comments

0

You can use negative indexes to access elements from last as:

var last = myArray[-1]

1 Comment

It is displaying "undefined"
0

If you are purely interested in the last element of a JavaScript Array you can use .pop()

var arr = ['first', 'second', 'last'];
var item = arr.pop();
console.log('accessed item: ', item);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.