Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find last element of an array without modifying source array in Vanilla Javascript

I have an array contains

const data = ['a', 'b', 'c', 'd'];

how to find the last element, result should be 'd'

like image 659
Syam Prasad Avatar asked Nov 28 '22 19:11

Syam Prasad


2 Answers

Using the function slice + destructuring assignment.

const data = ['a', 'b', 'c', 'd'],
      [last] = data.slice(-1);

console.log(last);
like image 200
Ele Avatar answered Dec 05 '22 03:12

Ele


You could slice from the end (negative index) and get the item of the array.

const data = ['a', 'b', 'c', 'd'];

console.log(data.slice(-1)[0]);
like image 27
Nina Scholz Avatar answered Dec 05 '22 02:12

Nina Scholz