The Find Method In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the The Find Method In JavaScript.
The Find Method In JavaScript
The find
method in JavaScript is a built-in function on the Array object that returns the value of the first element in the array that satisfies the provided testing function. If no element passes the test, undefined
is returned.
Syntax:
array.find(function(currentValue, index, array) {
// code to determine if element is the desired value
return element;
});
Where:
function
is the callback function that will be executed for each element in the array.currentValue
is the current value being processed in the array.index
is the index of the current value being processed in the array.array
is the original array thatfind
was called upon.
find Method To Find The First Positive Number In An Array
Here’s an example of using the find
method to find the first positive number in an array:
let numbers = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5];
let firstPositive = numbers.find(function(currentValue) {
return currentValue > 0;
});
console.log(firstPositive); // Output: 1
Output
1
Here’s another example of using the find
method to find an object in an array based on a specific property:
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Jim' }
];
let user = users.find(function(currentValue) {
return currentValue.id === 2;
});
console.log(user);
Output
{ id: 2, name: 'Jane' }
And here’s an example of using the find
method with an arrow function for conciseness:
let numbers = [1, 2, 3, 4, 5];
let firstEven = numbers.find(currentValue => currentValue % 2 === 0);
console.log(firstEven);
Output
2
Conclusion
If you liked this post The Find Method In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.