I've been exploring ways to search within an array while iterating through it. One method I stumbled upon is the find()
method.
Take a look at this example:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
Now, I want to find a specific fruit dynamically, but I'm struggling with implementing it. Basically, I'm aiming for something like this:
function findCherries(fruit, fruitName) {
return fruit.name === fruitName;
};
inventory.find(findCherries('cherries'))
//"true is not a function"
Is there a way to pass an argument to the find()
method in order to search based on that parameter? If not, what alternative method could I use to search for objects within an array dynamically?