Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active November 1, 2021 13:29
Show Gist options
  • Save acidtone/443af5d0efc720e19e56c9cc55f31521 to your computer and use it in GitHub Desktop.
Save acidtone/443af5d0efc720e19e56c9cc55f31521 to your computer and use it in GitHub Desktop.
Spoilers: Find an object in an array

Spoilers: Finding an array item that matches an object property

This is a potential answer to the exercise: Find an object in an array.

Stretch Activities

  • Try validating the user input before testing:
    • inputValue value missing: "Please enter a Character Class";
  • The return statement in the if/else blocks is redundant. Refactor this code to use the least code possible.
// 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
}
];
// Find a guild member with a class that matches the inputValue
const matchingCharacter = guild.find(function(character) {
if (inputValue === character.class) {
// Assign `character` to `matchingCharacter`
return true;
} else {
// Move to the next `character`
return false;
}
});
// 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