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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay