When an array contains objects, you can use a higher order array method, such as Array.find()
, to find an object that matches a particular property value.
Array.find()
loops through an array of objects and expects a Boolean return value:- If
true
is returned, the loops stops andArray.find()
returns the current item; - If
false
is returned, the loop continues to the next item; - If no items are found by the end of the loop,
Array.find()
returnsundefined
.
- If
- This method is considered a higher order function, meaning it hides (abstracts) information so we can tackle a problem at a higher (more abstract level). In this case,
Array.find()
hides the fact that it's looping through the array (and that it operations differently based on a boolean result).
- Download or fork/clone this Gist into your workspace.
- Using conditional statements and the
Array.includes()
method, test if the entered command line value exists in thecharacterClasses
array:-
If
true
log the following to the console:"[inputted value]" is a valid Character Class!`
-
If
false
log the following to the console:"[inputted value]" is NOT a valid Character Class! Please try again.`
-
Try validating the user input before testing:
- inputValue
value missing: "Please enter a Character Class";
A potential answer to this activity.