Subscribe

JavaScript find() method

โœ๏ธ

JavaScript find method, how it works and why you need it

29 Nov, 2020 ยท 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 },
];

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 }

This can also be written as a one-liner:

const found = items.find((item) => item.price < 10);

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',
};

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',
  },
];

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' }

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1513 devs and subscribe to my newsletter