4

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!

Fabian Sierra
  • 766
  • 1
  • 8
  • 22

3 Answers3

17

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.

Community
  • 1
  • 1
kind user
  • 40,029
  • 7
  • 67
  • 77
  • Just a pointer, next time if you see such a basic question, please look for possible duplicates and close it as duplicate. Its a bad practice to answer a dupe. :-) – Rajesh Feb 21 '17 at 13:35
  • @Rajesh If only I could close the question and mark it as duplicate, I would do it immediately. I just need more rep points to do it. – kind user Feb 21 '17 at 13:37
  • You could share dupe as comment so others who have reps could close it. – Rajesh Feb 21 '17 at 13:38
  • @Rajesh Right. Thank you. – kind user Feb 21 '17 at 13:39
1

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


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

Use slice -2

guradio
  • 15,524
  • 4
  • 36
  • 57
0

aray.prototype.splice() also

Note: Splice it will update the original array also

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

console.log(array.splice(-2));
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • Whats the difference between your answer and other answers? A user with your rep should know to read other answers before posting – Rajesh Feb 21 '17 at 13:36
  • @Rajesh `splice` vs `slice` – Sankar Feb 21 '17 at 13:37
  • *I am trying to obtain with slice() function* OP is looking for `slice`. Also splice will update original array – Rajesh Feb 21 '17 at 13:39
  • I said `splice` **also** can do this. Yes. it will affect original array also. i will update my content. – Sankar Feb 21 '17 at 13:49