This page looks best with JavaScript enabled

Search using Array.find() in Javascript

 ·   ·  ☕ 1 min read

Are you doing array search using the old school for-loops? Time to change, kid.

Consider this array -

1
2
3
4
5
const fruits = [
  { name: "apple", color: "red" },
  { name: "orange", color: "orange" },
  { name: "pear", color: "green" }
];

To search for a specific value -

1
2
3
4
console.log(fruits.find(val => val.name == "pear"));
// { name: 'pear', color: 'green' }
console.log(fruits.find(val => val.name == "grapes"));
// undefined

We use the Array.find method to retrieve search results. The argument for find takes a function which has the condition for find.

In our case we pass a val which represents each item in the array, and compare the name prop to the given value. find returns the matched item or undefined.

We typically use a simple for loop with equality operator or a for-each to return array element with matching criteria. While Array.find() also iterates through the array, it is more intuitive and easier to read.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things