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

313
Views
Reductor de Javascript, ¿cómo evitar que el operador && restablezca los valores?

Codificador aficionado aquí, nuevo en reductores.

Tengo una aplicación que agrega objetos a una matriz, con reductores que capturan la cantidad del valor de posición de cada objeto.

Lo siguiente funciona hasta cierto punto, cuando agrego dos entidades 'Att', la cantidad de totalAtt equivale a dos, pero cuando agrego otro valor de posición, la cantidad totalAtt se restablece a cero. Lo mismo para todos los valores de posición.

Descubrí que el operador && está restableciendo mi valor inicial a falso, dada su naturaleza booleana.

¿Alguien sabe cómo modificar el código para capturar las cantidades sin restablecer los valores?

 const totalGK = get(team).reduce( (a, b) => b.position === "GK" && a + b.qty, 0 ); const totalDef = get(team).reduce( (a, b) => b.position === "Def" && a + b.qty, 0 ); const totalMid = get(team).reduce( (a, b) => b.position === "Mid" && a + b.qty, 0 ); const totalAtt = get(team).reduce( (a, b) => b.position === "Att" && a + b.qty, 0 ); return { totalGK, totalDef, totalMid, totalAtt }; }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Al reducir, siempre devuelve el nuevo valor del acumulador. En su caso, agrega un valor al acumulador anterior para obtener el nuevo valor. Por lo tanto, siempre debe tomar a (el acumulador) y agregar 0 ( b.position === something es false, so it's casted to 0) o el número si la condición es true .

 const totalGK = get(team).reduce( (a, b) => a + (b.position === "GK" && b.qty), 0 ); const totalDef = get(team).reduce( (a, b) => a + (b.position === "Def" && b.qty), 0 ); const totalMid = get(team).reduce( (a, b) => a + (b.position === "Mid" && b.qty), 0 ); const totalAtt = get(team).reduce( (a, b) => a + (b.position === "Att" && b.qty), 0 );

Sin embargo, hay una forma más corta y legible de abordar esto, reducir el team a un objeto, usar los valores de position como claves y agregar la qty al valor anterior de la clave. Para obtener las constantes, desestructura el objeto creado por reduce y usa 0 como valores predeterminados.

Ejemplo:

 const get = arr => arr; const team = [{ position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }]; const { GK: totalGK = 0, Def: totalDef = 0, Mid: totalMid = 0, Att: totalAtt = 0, } = get(team).reduce((acc, obj) => ({ ...acc, [obj.position]: (acc[obj.position] || 0) + obj.qty }), {}); console.log(totalGK); // 6 console.log(totalDef); // 0 console.log(totalMid); // 0 console.log(totalAtt); // 9

about 4 years ago · Juan Pablo Isaza Report

0

Funcionaría mejor usando un operador ternario, por lo que siempre devuelve un valor de su función. Algo como esto

 const totalGK = get(team).reduce( (a, b) => b.position === "GK" ? a + b.qty : a, 0 );
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!