In this post, we are going to understand Array find() in JS ES6. The array. find() is used to find the first element from the array which passes the given test function
What is array.find()
Array. find() method is introduced in JS ES6. It returns the value of the first occurrence of the array element that passes the given test function.
Array. find() method run a test function for each element of the array. If the element passes the given test function then it returns the value of the element else returns undefined.
Syntax for array.find()
arr.find(callback(element, index, array),thisArg)
Parameters :
The ES6 find() method takes two parameters
- Callback: The function runs each element of the array. The callback takes these parameters.
- element : The current array element.
- Index : Index of current array element.
- array : The array on which find() method is called.
- thisArg : The object is used as this inside callback function
Return Value
The array. find() method runs a callback function for each element of the array until it returns true. If the callback function returns true then the find() method returns the element and terminates the searching else it returns undefined.
Example of ES6 array.find() methods
Find number divisible by 5
In this example, we are using the find() method to search the first array element that is divisible by 5.
Example
const array = [15, 20, 8, 130, 44];
const ele_found = array1.find(element => element%5==0);
console.log('array elellmet divible by five:',ele_found);
Output
array elellmet divible by five : 15
Find an element array of string
In this example, we are using the find() method to search the element in the string array that starts with the letter ‘a’. The array.find() method use fruit => fruit.startsWith(“a”)) callback function check for each element whichever element return true, the value of element will return .
Example
const fruits = [
"apple",
"banana",
"kiwi",
"orange"
];
const fruit_name = fruits.find(fruit => fruit.startsWith("a"));
console.log('fruit name start with a:',fruit_name);
Output
fruit name start with a: apple
Find element in Array of objects
In this example, we are finding an element in an array of objects using the JavaScript find() method.
const subjects = [
{subject :"Math",marks:90},
{subject:"Physics",marks:99},
{subject :"Chem",marks:100}
];
const sub_name = subjects.find(s => s.marks>90);
console.log('subject marks greater than 90:',sub_name);
Output
subject marks greater than 90: { subject: 'Physics', marks: 99 }
Summary
In this post, we have learned how to use Array find() in JS ES6 with example