Get last n elements of an array
How to solve it
We have seen in another challenge that you can extract certain elements from an array using the slice method. The same approach can be applied here by making use of the fact that the slice method accepts negative parameters.
Remember that we can remove the first n elements from an array by simply passing n+1 as the starting parameter of the slice method:
const arr = [0,1,2,3,4]; console.log(arr.slice(1)); // output: [1,2,3,4]
If we know the how many elements there are in the array, we can use the exact same approach to get the last n elements. The array
[0,1,2,3,4]
has 5 elements. If we want to get the last 2 elements, we can simply remove the first 3: const arr = [0,1,2,3,4]; console.log(arr.slice(3)); // output: [3,4]
But, in this challenge, the number of array elements is different in each test case. We could identify the correct number using the array.length method. But, there is a much simpler way. The array.slice method accepts negative parameters. If you pass a negative number as first parameter, slice identifies the starting position by counting backwards from the end of the array. If you want the last n elements of an array, you simply execute
array.slice(-n)
: const arr = [0,1,2,3,4]; console.log(arr.slice(-2)); // output: [3,4]
This works no matter how many elements there are in the array.