Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

72
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda