- Demonstrate
find()
- Use
find()
to isolate a specific result
In any programming language, you'll perform operations on arrays. Looking in
an Array
for a sub string or set of characters is a common task. Sometimes
you need to look for a specific item in the array, and return it. Given a
string or array you can iterate over its elements and perform actions. ES6
introduced a few new Array
methods--one of them being find()
.
The find
function behaves similar to others in JavaScript (like filter
)
that want a truthy/falsey result. find
returns the first
element for which the function returns true, a single element.
[1,3,5,6,8].find( e => e % 2 === 0 )
//=> 6
Note: You could have multiple matches, but find
returns only the first
element. This could lead to some bugs if you're not careful.
let roommates = ["jess", "winston", "winston", "nick"];
roommates.find( s => s === "winston" )
//=> winston
roommates.filter( s => s === "winston" )
//=> [winston, winston]
Let's create a function that uses the method find()
to single out a specific
result in game record data for the football team Kansas City Chiefs. We want to
find out if, at any point in the team's existence, they've had a win in the
Superbowl. Our data looks like this:
const record = [
{year: "2018", result: "L"},
{year: "2017", result: "W"},
{year: "2016", result: "N/A"}
//...
]
Write a function called superbowlWin()
in index.js
that:
- Receives 1 argument, an
Array
of JavaScriptObject
s - Each object has two properties:
year
andresult
- Use
find()
to test eachObject
to see if theresult
is"W"
— a win! superbowlWin()
should return theyear
when the win occurred (if it occurred at all!). If no win is found, it should return, sadly,undefined
Run the tests using learn
.
Array.find()
is a built-in function in JavaScript which is used to get the
value of the first element in the array that satisfies the provided condition.
With this, you can quickly check all the elements of the array and return the
first match.