Finding the element or occurrence in a js array is a very frequently asked question. For this you can use the find() function; In this tutorial, we will show you how to find or get the first occurrence element in a JavaScript array using the js array method.
If you want to 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.
How to Get First Element From Array in JavaScript
The Find() method helps you to get the first occurrence of an element in the array that satisfies the given specific test condition.
Syntax of the find()
method
The following syntax demonstration of the find()
method:
find(callback(element[, index[, array]])[, thisArg])
Parameters
array
: The array you want to search through.callback
: A function that defines the condition for the search. It takes three arguments:element
(the current element being processed),index
(optional, the index of the current element), andarray
(optional, the array being processed).thisArg
(optional): An object to which thethis
keyword can refer in thecallback
function.
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.
Examples of Get First Element From Array in JavaScript
First, you have an array with some items. Let’s say it’s an array of numbers.
let numbers = [1, 2, 3, 4, 5];
Now, you want to find the first odd number from this, you can use it:
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.find(e => e % 2 == 1));
Output:
1
Another example, get the first even number from this, 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}
Conclusion
In this tutorial, you have learned how to use the js Array find() method to find or get first occurrence of an element in an array.