Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active July 26, 2022 21:42
Show Gist options
  • Save acidtone/fec626b5701beeed49cea776fc354325 to your computer and use it in GitHub Desktop.
Save acidtone/fec626b5701beeed49cea776fc354325 to your computer and use it in GitHub Desktop.
JS Activity: Find an object in an array

JS Activity: Finding an object in an array

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.

Key Takeaways

  • Array.find() loops through an array of objects and expects a Boolean return value:
    • If true is returned, the loops stops and Array.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() returns undefined.
  • 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).

Instructions

  1. Download or fork/clone this Gist into your workspace.
  2. Using conditional statements and the Array.includes() method, test if the entered command line value exists in the characterClasses 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.`
      

Stretch Activity

Try validating the user input before testing: - inputValue value missing: "Please enter a Character Class";

Spoilers

A potential answer to this activity.

// Accept command line input
const inputValue = process.argv[2];
// Define data array
const guild = [
// Item 1
{
// general
id: 1,
name: 'Harry',
class: 'wizard',
race: 'elf',
// stats
strength: 16,
dexterity: 14,
constitution: 12,
intelligence: 14,
wisdom: 16,
charisma: 10,
// Modifiers
poisoned: false
},
// Item 2
{
// general
id: 2,
name: 'Ryan Reynolds',
class: 'bard',
race: 'human',
// stats
strength: 12,
dexterity: 16,
constitution: 14,
intelligence: 6,
wisdom: 10,
charisma: 20,
// Modifiers
poisoned: true
},
{
// general
id: 3,
name: 'Spry',
class: 'rogue',
race: 'elf',
// stats
strength: 6,
dexterity: 18,
constitution: 10,
intelligence: 18,
wisdom: 14,
charisma: 8,
// Modifiers
poisoned: false
}
];
// Your code here
// Log the results
if (matchingCharacter) {
console.log(`Found a guild member with a class of ${inputValue}: \n${matchingCharacter}`);
} else {
console.log(`Couldn't find any guild members with a class of ${inputValue}. Please try again.`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment