'How the get the last element in an array items using JavaScript
I have a list of array items like this:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
]
How can I return / log the last element: { c: 3 }
Here's what I've tried so far:
let newarray = items.map((item) => {
console.log(item);
})
console.log(newarray);
Solution 1:[1]
Update 2021
You can use the Array.at() method, which was moved to Stage 4 in Aug, 2021
['a','b','c'].at(-1) // 'c'
Further Reading
Solution 2:[2]
just log the length minus 1, nothing to do with es6:
console.log(items[items.length - 1])
Solution 3:[3]
If your list has 3 items, the length is 3 but the last item index is 2, since arrays start at 0, so simply do this:
console.log(items[items.length - 1]);
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Solution 4:[4]
I want to let you try something different:
console.log(items.slice(-1));
Solution 5:[5]
try this
console.log(items[items.length - 1]);
Solution 6:[6]
It's not required to use ES6 to perform the operation you're asking about. You could use either of the following:
/**
* The last value in the array, `3`, is at the '2' index in the array.
* To retrieve this value, get the length of the array, '3', and
* subtract 1.
*/
const items = [1, 2, 3];
const lastItemInArray = items[items.length - 1] // => 3
or:
/**
* Make a copy of the array by calling `slice` (to ensure we don't mutate
* the original array) and call `pop` on the new array to return the last
* value from the new array.
*/
const items = [1, 2, 3];
const lastItemInArray = items.slice().pop(); // => 3
However, if you are dead set on using ES6 to retrieve this value we can leverage the spread operator (which is an ES6 feature) to retrieve the value:
/**
* Create new array with all values in `items` array. Call `pop` on this
* new array to return the last value from the new array.
*
* NOTE: if you're using ES6 it might be a good idea to run the code
* through Babel or some other JavaScript transpiler if you need to
* support older browsers (IE does not support the spread operator).
*/
const items = [1, 2, 3];
const lastItemInArray = [...items].pop(); // => 3
Solution 7:[7]
Update - October 2021 (Chrome 97+)
Proposal for Array.prototype.findLast and Array.prototype.findLastIndex is now on Stage 3!
You can use it like this:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
];
const last_element = items.findLast((item) => true);
console.log(last_element);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | bryan60 |
| Solution 3 | Robouste |
| Solution 4 | MedaiP90 |
| Solution 5 | Max Ivanov |
| Solution 6 | |
| Solution 7 | NeNaD |
