I have following code where I get 4 different attributes, I need to check each if its true and increment the count
var count = 0;
if (props.isApple) {
count += 1;
}
if (props.isOranges) {
count += 1;
}
if (props.isBanana) {
count += 1;
}
if (props.isJackfruit) {
count += 1;
}
console.log(count);
Is there any simple or nicer way of doing this? Any suggestions??
Looks like a job for reduce
const props = {
isApple: true,
isOranges: false,
isBanana: true,
isJackfruit: true
} // 3 true values
const checks = ["isApple", "isOranges", "isBanana", "isJackfruit"];
const count = checks.reduce((sum, check) => sum + (props[check] ? 1 : 0), 0);
console.log("count", count)
This iterates the list of checks and adds one to the sum if that property is truthy in props.
If you wanted it to be more dynamic and inclusive of all prop properties, you could define checks as...
const checks = Object.keys(props)
Since you've tagged this with reactjs, I'd use the memo hook to avoid unnecessary recalculation
import { useMemo } from "react";
const checks = ["isApple", "isOranges", "isBanana", "isJackfruit"];
const YourComponent = (props) => {
const count = useMemo(() =>
checks.reduce((sum, check) => sum + (props[check] ? 1 : 0), 0),
[ props ]
);
// etc
}