📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Syntax
arr.find(callback[, thisArg])
- callback - Function to execute on each value in the array, taking three arguments:
- element - The current element being processed in the array.
- index - Optional. The index of the current element being processed in the array.
- array - Optional. The array find was called upon.
- thisArg - Optional. Object to use as this when executing the callback.
JavaScript Array.find() Method Examples
Example 1: Simple Array.find() Example
var array1 = [15, 20, 25, 30, 35];
var found = array1.find(function(element) {
return element > 12;
});
console.log(found);
15
Example 2: Find an object in an array by one of its properties
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function isCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
{ name: 'cherries', quantity: 5 }
Example 3: Find a prime number in an array
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
Comments
Post a Comment
Leave Comment