We can use two array methods to help us get the previous items from an array:
- Array.indexOf()
- Array.slice()
Array.indexOf()
We use it to get the index of an item in an array. In our case, we want to get the index of the current item. Returns -1 if the item is not found.
Array.slice()
We use it to get a part of an array. In our case, we want to get the previous items from the current item. Returns an empty array if the item is not found.
Example:
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
const currentCar = 'Honda';
const index = cars.indexOf(currentCar); // two
const previousCars = cars.slice(0, index); // ['Ford', 'Chevy']
You can find more information about slice and indexOf type in the Mdn web docs. - Mdn Docs - slice and Mdn Docs - indexOf
Thanks for reading this article.
If you liked this article, please vote and comment.
Follow me on Twitter
Top comments (0)