In this tutorial, you will learn JavaScript find()
method and how to search the first occurrence element in an array using this javascript array method.
If you will use indexOf()
or lastIndexOf()
method to find the value in an array, These methods only allow you to find one value at a time in a javascript array.
You can use the new method find()
to find first occurrence of an element in an array. Instead of these indexOf()
or lastIndexOf()
method. Because in es6 enhance the capability to finding the elements in the javascript array
find()
methodThe following syntax demonstration of the find()
method:
find(callback(element[, index[, array]])[, thisArg])
The find()
takes two parameters:
callback
function and it’s optional.this
inside the callback
.callback
The callback
is a function to execute on each element of the array. It accepts 3 parameters:
element
is the current element of an array.index
the index of the current element of an array.array
the array that the find()
was called upon.thisArg
is the object to use as this
inside the callback
.
For each element of an array, The find()
executes the callback
function until the callback
returns a truthy value. In this case, the find()
immediately returns the value of that element. Otherwise, it returns undefined
.
Note that, JS find()
method is truly different from the findIndex()
method. The findIndex()
method is used to search the position of an element in an array.
find()
Suppose you have a numeric array and want to search the first odd number in it, you can use these find()
method for these.
See the following example:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.find(e => e % 2 == 1));
Output:
1
If you want to find first even number in an array, you can find the following:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.find(e => e % 2 == 0));
Output:
2
Suppose that you have a list of computers objects with name
and price
properties as follows:
let computers = [{
name: 'Dell',
price: 60000
}, {
name: 'HP',
price: 50000
}, {
name: 'Apple',
price: 80000
}];
The following javascript code uses the find()
method to find the first computer whose price is greater than $ 60000.
let computers = [{
name: 'Dell',
price: 60000
}, {
name: 'HP',
price: 50000
}, {
name: 'Apple',
price: 80000
}];
console.log(computers.find(c => c.price > 60000));
Output:
{name: "Apple", price: 80000}
In this tutorial, you have learned how to use the JavaScript Array’s find()
method and using this method how to find the first occurrence of an element in an array.
#javascript #programming