How to get all previous items of an array in js from a certain value

ianfelix

Ian Felix

Posted on March 23, 2022

How to get all previous items of an array in js from a certain value

We can use two array methods to help us get the previous items from an array:

  1. Array.indexOf()
  2. 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']
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
ianfelix
Ian Felix

Posted on March 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related