How to find a single item in an array with JavaScript

To find a single (specific) item in an array with vanilla JavaScript you can use the ES6 method Array.find().

Let’s say you have an array of list items, in this case its vegetables. Now you want to find the carot from the list:

const vegetables = ["broccoli", "carot", "kale", "spinach"]

// Find carot in array
let carot = vegetables.find(function(vegetables) {
  return vegetables === "carot"
})

console.log(carot)
// "carot"

How the code works:

  • First you declare a variable carot
  • Then you assign the vegetables variable to it, and attach the Array.find() method and tell it to return the exact string "carot"
  • Log out the result

Note 1: the triple equals operator === checks for both value equality and type equality.

Note 2: JavaScript is case sensitive. If your array items use capital letters, you need to use uppercase letters in your Array.find() method as well.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on