1

on developer.mozilla i found an example of working with array find:

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

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

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }

I have an cart Class with an array of objects, so, i am having a function checkQuantity which should return whatever item satisfies the condition. Also i am having same function where i need to find.

i tried to implement this approach from mozilla, and i did like this:

itemSearch(item) {
        return item.id === this.id &&
            item.color === this.color &&
            item.size === this.size
    } // method which i need

and i am using it like this:

 checkQuantity() {
        return this._cart.find(this.itemSearch()).quantity < this.stockCount();
    }

Where i obtain undefined, however i know for sure it must find , because if i use .find(element => conditions) instead of that method, it works.

so, my Question is why it does not work? Sorry for bad english.

4
  • do you have a data set with class and (non)working example? Commented Apr 10, 2021 at 11:56
  • 1
    Take another look at the example you got inspiration from. They do .find(isCherries), not .find(isCherries()) Commented Apr 10, 2021 at 11:56
  • @blex, my first try was without () , it does not work anyway. Commented Apr 10, 2021 at 11:57
  • 1
    @iftwMZ, you have to bind to this explicitly: this._cart.find(this.itemSearch.bind(this)). Otherwise you lose the correct context and this will point to window instead. Commented Apr 10, 2021 at 11:58

1 Answer 1

1

By using this, you need to specify this as well for Array#find, beside not to use the result of the call of the function.

checkQuantity() {
    return this._cart.find(this.itemSearch, this).quantity < this.stockCount();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works. thank you so much. Waiting 10 minutes and i mark as answered!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.