Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

69
Views
React js/ javascript code refactor for loop/switch

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??

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!