Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last two positions of an array [duplicate]

I would like to know how can I obtain the last two elements of this array like this:

array = [1,5,7,8,10,12,23,24];

I am trying to obtain with slice() function but it doesn´t work for me, beacuse I always I want to obtain the last two positions.

array = [23,24];

I hope that anyone can help me in this question.

Regards!

like image 255
Fabian Sierra Avatar asked Dec 07 '22 19:12

Fabian Sierra


2 Answers

Use Array#slice with negative index.

var array = [1,5,7,8,10,12,23,24];

console.log(array.slice(-2));

You can learn more about this method also here.

like image 76
kind user Avatar answered Dec 11 '22 10:12

kind user


array = [1,5,7,8,10,12,23,24];


console.log(array.slice(-2))

Use slice -2

like image 26
guradio Avatar answered Dec 11 '22 09:12

guradio