Find method in Javascript
In this tutorial, we will learn about how to use and when to use the Find() method in JavaScript.
WE can use the find method to retrieve one element of an array based on a condition.
unlike the filter method, the find method will actually not return a new array but it will only return the first element in the array that satisfies the condition
For example,
Suppose we have an array as follows:
let arr = [10,11,47,58,55];
Now we wan'ts to find first number which is greater than 20, so we can do this using filter as follows:
const first = arr.find(mov => mov > 20);
console.log(first);//47
Find elemted from Array of Objects:
We can also find any elemnent from array of object based on specfic condition.
Example:
let members = [
{
owner: 'John doe',
interestRate: 10,
pin: 114,
},
{
owner: 'James',
interestRate: 12,
pin: 144,
},
{
owner: 'Jason',
interestRate: 11,
pin: 148,
}
];
const result = members.find(ele => ele.pin === 144);
console.log(result);
//{owner: "James", interestRate: 12, pin: 144}
Difference between find and filter:
- Filter returns all the elements that match the condition while the find method only returns the first one
- Filter method returns a new array while find only returns the element itself and not an array