In the previous blog post, we learned the map method, which is one of the most used methods among Javascript array methods. In this article, we will continue with array methods and learn the find array method. Let’s get started.
What is the Javascript find() Method?
Find() method is a javascript array method that returns the first value it finds after searching the array based on the specified condition. If no element suitable for the condition is found, it will return the undefined value.
Now let’s look at the usage structure of the find method
array.find(function(currentValue, index, array),thisValue)
- currentValue : Specifies the value of the element being processed.
- index : Specifies the index value of the processed element.
- array : Specifies the array value being processed.
- thisValue : Specifies the this value to be used when the specified operation is performed, i.e. when the callback function is executed.
Important Warnings
- The Find() method does not modify the default array. It searches the array and returns the first value it finds.
- The find() method will not work on arrays with no elements.
- If the searched element is not found in the array, the result will be returned as undefined.
EXAMPLES
Find A Standard Example
Let’s write the code that finds the first element with a number value greater than 17 in an array of numbers using the find() method.
const numberArray = [2, 5, 10,15,17,54,18,19];
const findElement = numberArray.find((element) => element > 17);
console.log(findElement);
Output;
Yes, as you can see in the output below, it took the first value greater than 17 in the array and showed us the value 54 as output. It processes each value one by one and if the result is true, it returns that value and ends the process. If false, it moves on to the next element. When it examines the last element, if the operation is not true, it will return the result as undefined. This is the main logic of the Find method.
Now let’s see an example of how frontend developers use the find() method in react projects in their daily work life.
Find Method Example Project Usage
In the endpoint where there are blog posts, the fields where the user will be displayed in general are also sent in the same endpoint. But in jsonplaceholder, it is divided into two endpoints as posts and users and an association is made between them. A user can have many posts, which means one-to-many associations. If you are asking how to use the find method here, let’s move on to it ?
Let’s first understand the following codes. We have created a data state for posts. We also create a state for users. Then we transfer the data from the “https://jsonplaceholder.typicode.com/users” endpoint to the users state using fetch. Now we have both posts data and users data.
const [data, setData] = useState([]);
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((resPost) => {
setData(resPost);
});
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((resUsers) => {
setUsers(resUsers);
});
}, []);
Now how will the one-to-many association be here. If you have noticed, there is a field called userId in each object in the posts data. Here, using this field, we will make an association with the users data coming from the users endpoind. Now we are moving on to it…
const usernameValue = (id) => {
return users.find((user) => user.id === id).username;
};
return (
<div id="content">
<h1>Map</h1>
<div className="card">
{data &&
data.map((item) => {
return (
<div className="card-item" key={item.id}>
<span className="card-username">{usernameValue(item.userId)}</span>
<h2 className="card-title">{item.title}</h2>
<p className="card-description">{item.body}</p>
</div>
);
})}
</div>
</div>
);
Above we created a function called usernameValue. Let me explain what exactly this function will do. While printing the posts data in Return, I also want to print the name of the user who prepared that post. I send the userId value in the post to the usernameValue function. Then the usernameValue function returns the first value whose user.id is equal to the id I sent by using the find method in users for me.
This value is all the data value of that user. But what I need is only the username field value, so I add the username value to the end of the find method. In this way, the usernameValue function returns the username value of the user who wrote that post depending on the id sent to me. The explanation was a bit complicated, but I hope it was understood.
I am also sharing the final version of the code with you.
import userEvent from "@testing-library/user-event";
import { useEffect, useState } from "react";
const FindMethod = () => {
const [data, setData] = useState([]);
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((resPost) => {
setData(resPost);
});
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((resUsers) => {
setUsers(resUsers);
});
}, []);
const usernameValue= (id) => {
return users.find((user) => user.id === id).username;
};
return (
<div id="content">
<h1>Find</h1>
<div className="card">
{data &&
data.map((item) => {
return (
<div className="card-item" key={item.id}>
<span className="card-username">{usernameValue(item.userId)}</span>
<h2 className="card-title">{item.title}</h2>
<p className="card-description">{item.body}</p>
</div>
);
})}
</div>
</div>
);
};
export default FindMethod;
#content {
width: 100%;
height: 100%;
}
.card-item {
width: 700px;
min-height: 200px;
height: auto;
border: 2px solid #ccc;
box-shadow: 0 2px 10px 2px #ccc;
margin: 20px auto;
padding: 20px;
text-align: center;
border-radius: 10px;
}
.card-username {
font-size: 18px;
font-weight: 600;
color: #fff;
background-color: #e74c3c;
padding: 10px 20px;
border-radius: 10px;
}
.card-title {
font-size: 24px;
font-weight: 800;
color: ;
}
.card-description {
font-size: 18px;
line-height: 1.4;
font-weight: 500;
color: #333;
}
Remember, if you are looking for 1 unique element in an array, the find method is one of the best methods. But if you want to see all values conditionally in the search result, that is, if you want to get all numbers greater than 17 as in the standard example above, I recommend looking at the filter method for this.
The End
In this article, I have given you information about the find method, which is a Javascript array method. You have also learned how to use this method in projects using the React library. I wish you to use the find method in your projects a lot and I hope to see you in my next blog post. Goodbye.