Iggy Iggy -3 years ago 104
Javascript Question

How to give javascript find() method an argument to search?

I am trying to figure out a way to do search while iterating an array. I came across


Here is the example given:

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}

function findCherries(fruit) {
return fruit.name === 'cherries';

// { name: 'cherries', quantity: 5 }

I need find a dynamic fruit name, but I can't figure out how to do it. In short, I am trying to do something like:

function findCherries(fruit, fruitName) {
return fruit.name === fruitName;

//"true is not a function"

Is there a way to give
an argument and find a match base on that argument? If not, what method allows me to search an array of object dynamically?

Answer Source

With a closure (your function must return a function) like this:

function findFruitByName(name) {
    return function(fruit) {
        return fruit.name === name;

// {name: "cherries", quantity: 5}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download