Bart
Bart

Reputation: 77

Better way to return boolean

I wrote this wanting to match if a string matched a string inside an array. using find() it returned the match but I just wanted a boolean so i wrote an if statement. Any tips or hints on how to rewrite this cleaner to get a boolean?

the prop watchName comes from a map() of data of watches in inventory

.map(watch => (
            <WatchItem
              isInCart={this.isInCart(watch.name)}
.....

.

isInCart = watchName => {
  const hasMatch = this.props.cart.find(watch => watch.item === watchName);
  if (hasMatch) {
    return true;
  } else {
    return false;
  }
};

To get better idea of whats inside this.props.cart i added it below It is an array of objects. The picture shows index[0] and index1 the added cart item

picture of this.props.cart

I will read mdn docs again but thought be good to post in case someone can quickly answer. Advice appreciated.

Upvotes: 1

Views: 116

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can use this too

  isInCart = watchName => this.props.cart.includes(watchName);

Upvotes: 2

kind user
kind user

Reputation: 41893

Return it directly. Use a double negation !! or just wrap it inside Boolean.

isInCart = watchName => 
  !!this.props.cart.find(watch => watch.item === watchName);

either

isInCart = watchName => 
  Boolean(this.props.cart.find(watch => watch.item === watchName));

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370679

You can use Array.prototype.some instead, which checks whether any element in an array satisfies a condition, and returns a boolean:

isInCart = watchName => this.props.cart.some(watch => watch.item === watchName);

Upvotes: 3

Related Questions