EN
JavaScript - get second last item in array
0 points
In this article, we would like to show you how to get the second last item in an array working with JavaScript.
Below we present two solutions on how to do that:
- Using square brackets
[]
, - Using
slice()
method.
In this section, we use the array length
property to count the second last index in array
. Then we can get the value of the last item.
xxxxxxxxxx
1
var array = ['a', 'b', 'c', 'd'];
2
3
var result = array[array.length - 2];
4
5
console.log(result); // 'c'
The below example shows the use of slice()
method with a negative indexing to get the second last item of the array
.
xxxxxxxxxx
1
function getItem(array) {
2
var items = array.slice(-2);
3
return items[0]; // returns item or undefined
4
}
5
6
7
// Usage example:
8
9
var array = ['a', 'b', 'c', 'd'];
10
11
var item = getItem(array);
12
13
console.log(item ); // 'c'