JavaScript find() method

β€” 3 minute read

permalink

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 permalink

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! permalink

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