The function and syntax of find()
is very much like the Array.filter method, except it only returns a single element. Another difference is when nothing is found, this method returns a value of undefined
.
So if you only need a single value, use find()
! When you need to find/return multiple values, reach for filter()
instead.
Using find()
is super easy! The only required parameter of this method is a testing function, and it can be as simple or complex as needed. In its most basic form:
array.find(testingFunction); // that's it!
Here’s a simple example with an array of strings:
const trees = [ "birch", "maple", "oak", "poplar" ];const result = trees.find(tree => tree.startsWith(“m”));
// “maple”
In non-shorthand, non-ES6 form:
const result = trees.find(function(tree) {
return tree.startsWith(“m”);
});// “maple”
We can use find()
to easily search arrays of objects, too!
const trees = [
{ name: “birch”, count: 4 },
{ name: “maple”, count: 5 },
{ name: “oak”, count: 2 }
];const result = trees.find(tree => tree.name === “oak”);
// { name: “oak”, count, 2 }
Using the same example, notice if we use find()
when a test has multiple results, we only get the first value found:
const result = trees.find(tree => tree.count > 2);// { name: “birch”, count: 4 }
This is an instance where you should probably use filter()
instead. See the difference?
Sometimes you’ll want to re-use the same find()
test function in multiple places. In that case, it can be really helpful to create a separate testing function.
Let’s demo this technique, expanding on our previous examples:
const deciduous = [
{ name: “birch”, count: 4 },
{ name: “maple”, count: 5 },
{ name: “oak”, count: 2 }
];const evergreens = [
{ name: “cedar”, count: 2 },
{ name: “fir”, count: 6 },
{ name: “pine”, count: 3 }
];// our testing function
const hasFiveOrMore = el => el.count >= 5;const decResult = deciduous.find(hasFiveOrMore);
// { name: “maple”, count: 5 }const evgResult = evergreens.find(hasFiveOrMore);
// { name: “fir”, count: 6 }
Simple, but powerful! 💪
Like filter()
, there is an optional index
parameter we can use. Here’s one last example, using it as part of our testing function:
const evergreens = [
{ name: “cedar”, count: 2 },
{ name: “fir”, count: 6 },
{ name: “pine”, count: 3 }
];// suppose we need to skip the first element
const result = evergreens.find((tree, i) => {
if (tree.count > 1 && i !== 0) return true;
});// { name: “fir”, count: 6 }
The index
is probably not something you’ll need often — but it’s great to have available at times.
Array.find
is a simple but incredibly useful method for searching JavaScript arrays.
Just remember: only use find
when you want a single element returned, and that it returns undefined
if nothing is found! Otherwise, use the filter
method when you need multiple elements returned.
Originally published by Daniel Stout at alligator.io
#javascript #web-development