Reputation: 33
If at least one of the values returned from the loop is true, the function must return true. How can I do this?
const addCart = () => {
for (let i = 0; i < props.cart.length; i++) {
return props.cart[i].domainName === props.domainName;
}
};
Upvotes: 0
Views: 79
Reputation: 5644
Try the following code.
const addCart = () => {
for (let i = 0; i < props.cart.length; i++) {
if (props.cart[i].domainName === props.domainName) {
return true;
}
}
return false;
};
The function returns true when the first equal property has been found. It gives you the possibility to obtain the result without checking all elements of the array.
Upvotes: 2
Reputation: 177
const addCart = () => props.cart.some(e=>e.domainName===props.domainName);
Upvotes: 1
Reputation: 253446
I'd suggest:
const addCart = () => {
// here we use Array.prototype.some(),
// which returns a Boolean; true if any
// of the array-elements match the provided
// assessment, or false if not:
return props.cart.some(
(cart) => cart.domainName === props.domainName
);
}
References:
Upvotes: 1