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.

Shreyas Pednekar
  • 1,285
  • 5
  • 31
  • 53

6 Answers6

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]);
Cory Kleiser
  • 1,969
  • 2
  • 13
  • 26
3

Try this:

var lastMessage = chats[chats.length - 1].message;
console.log(lastMessage);
Alex Baban
  • 11,312
  • 4
  • 30
  • 44
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);
2

You could write something like this:

someArray[someArray.length - 1]
qopa
  • 111
  • 4
0

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

var last = myArray[-1]
Naman Kheterpal
  • 1,810
  • 1
  • 9
  • 16
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);
dkaramazov
  • 204
  • 2
  • 9