Sometimes, we want to map array last item with JavaScript.
In this article, we’ll look at how to map array last item with JavaScript.
How to map array last item with JavaScript?
To map array last item with JavaScript, we check the items’ index in the map
callback.
For instance, we write
const newRows = row.map((rank, i, row) => {
if (i + 1 === row.length) {
// Last one.
} else {
// Not last one.
}
});
to call row.map
to check if index i + 1
is row.length
.
If it is, then the callback is called on the last item in row
.
Otherwise, it’s not called on the last object.
Conclusion
To map array last item with JavaScript, we check the items’ index in the map
callback.