DEV Community

Ian Felix
Ian Felix

Posted on

4 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay