Arrays are a special type of object that allows you to store multiple items in a single object.
You can find the first element of an array matching a condition using the array.find(condition)
statement in JavaScript.
This tutorial explains the different methods to find the first element of an array matching a condition in JavaScript.
Table of Contents
Find the First Element Of An Array Matching A Condition Using Array Find
The array.find() method returns the first element that matches a specific condition.
- If no item matches the condition, it returns
undefined
.
You can pass the desired function to the find()
method.
For example, to find the element that is greater than 4, you can pass the function element => {return element > 4;}
.
Use this method when you want to find the first item only once, even if it exists more than once in the array.
Code
const numArray = [1, 2, 3, 4, 5];
const firstElement = numArray.find(element => {
return element > 4;
});
console.log(firstElement);
Output
5 is the first element in the array that is greater than 4. Hence it is returned.
5
Find the First Element Of An Array Matching A Condition Using Array Filter
The array.filter() method creates a shallow copy of a portion of the array containing the items that pass a specific condition.
- When no elements pass the condition specified, an empty array is returned.
You can pass the desired function to the filter()
method.
For example, to find the element that is greater than 3, you can pass the function element => element > 3
. You’ll get an array. To find the first item in the array, you can use the index [0]
.
Use this method when you want to find all occurrences of the first item that passes a specific condition.
Code
const numarray = [1, 2, 3, 4, 5];
const elementsMatchingCondition = numarray.filter(element => element > 3);
console.log(elementsMatchingCondition);
console.log("First Element Matching Condition : " + elementsMatchingCondition[0]);
Output
The first array contains all the elements passing the specific condition.
You can find the first element from it using the [0]
.
[4, 5]
"First Element Matching Condition : 4"
Additional Resources
- Array.push() If Does Not Exist in Javascript – With Examples
- How To Get the last item in an array in JavaScript
- How to Add New Elements At the Beginning of the Array in JavaScript
- How to Get the First N Elements of An Array in JavaScript
- How To Check If A Value Exists At a Certain Index of an Array In JavaScript