JavaScript ES6 – Array find method
JavaScript array find()
is a method that exists on the Array.prototype
and was introduced in ECMAScript and is supported in all modern browsers.
JavaScript array find()
method searches your array and returns the first matching element, or undefined.
find()
return value is dynamic and could be of any JavaScript type that exists in the array. It could be a string
, number
, object
or any other type.
Think of JavaScript array find()
method as: “I want to find a particular element in my array.”
array find()
parameters
JavaScript array find()
method consists of following parameters:
- value – value of current element per iteration
- index – the element index, not common to use
Let’s see an example on how to use JavaScript array find()
method:
let arr = [9, 4, 24, 6];
const result = arr.find((value) => value % 2 === 0);
console.log(result);
// OUTPUT
// 4
In above example we are looking to find the first even number.
The result in this case is 4
, Since 4
is the first element in array that satisfies our condition value % 2 === 0
to be true
.
find()
on objects array
We can perform really complex operation using JavaScript array find()
method. One of most use cases of JavaScript array find()
is using in objects array.
Let’s see an example of find()
method for objects:
let people = [
{
name: "John",
age: 19,
},
{
name: "Mary",
age: 18,
},
{
name: "Bob",
age: 16,
}
];
const teenager = people.find((person) => person.age < 19);
console.log(teenager);
// OUTPUT
// {'Mary', age: 18}
In above example we are iteration thru people
object array and checking if any person age is person.age < 19
less than 19?
In this case {'Mary', age: 18}
is return as matching object
within the people
array.
array find
usage and tips
- Don’t forget to
return
values, otherwise it will beundefined
- Find method will look for first matching elements, It will return the value. Unlike filter method which returns as many elements as they satisfies the condition.
- As soon as the first matching element found, Find will exist the loop
- If no matching result was found, it will return
undefined
- Empty slots in the array are skipped
summary
You’ve now learned how to use Array find()
to find the first matching element in the array.
Remember as well, Find is similar to JavaScript filter method and JavaScript some method! If you want to know the different between find()
, filter()
and some()
methods. check out Difference between find, filter and some methods.
most used JavaScript array methods
Want to know the most common JavaScript array methods? See the list of methods below or read most common array method with examples.