DEV Community

loading...
Cover image for JavaScript find() method

JavaScript find() method

dailydevtips1 profile image Chris Bongers Originally published at daily-dev-tips.com ・2 min read

Today we are exploring the find() array method in JavaScript.
I find this method very similar to the some() method.

What it does is it searches the array for a specific hit, but instead of returning a boolean, it will return the first match it finds.

Using the Javascript find() method

Let's start by creating an array of items.

const items = [
  { name: 'T-shirt plain', price: 9 },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 }
];
Enter fullscreen mode Exit fullscreen mode

Let's find the first item that is under the price of 10.

const haveNames = items.find(item => {
  return item.price < 10;
});

// { name: 'T-shirt plain', price: 9 }
Enter fullscreen mode Exit fullscreen mode

This can also be written as a one-liner:

const found = items.find(item => item.price < 10);
Enter fullscreen mode Exit fullscreen mode

Some use cases could be the first blog-post with the same category.

To see this in action let's say we are currently viewing this article:

const blog = {
    'name': 'JavaScript find() method',
    'category': 'javascript'
}
Enter fullscreen mode Exit fullscreen mode

And we have an array of blog items like this:

const blogs = [
  {
    'name': 'CSS :focus-within',
      'category': 'css'
  },
  {
    'name': 'JavaScript is awesome',
      'category': 'javascript'
  },
  {
    'name': 'Angular 10 routing',
      'category': 'angular'
  }
];
Enter fullscreen mode Exit fullscreen mode

Now we can use find() to get the first blog item that is related to our one (javascript based).

const related = blogs.find(item => item.category === blog.category);
console.log(related);

// { name: 'JavaScript is awesome', category: 'javascript' }
Enter fullscreen mode Exit fullscreen mode

There you go, an example of how to use the find find() method in JavaScript.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Discussion (0)

pic
Editor guide