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

172
Vistas
Refactoring JS function and Removing conditional out of loop

As title explains im trying to understand the best way to refactor my function and also remove my if statement from the loop? Any guidance would be appreciated. As I have an idea that me else condition is useless.

function quantitySum(array) {
  let sum = 0;
  for (let i = 0; i < array[0].length; i++) {
    if (array[0].length > 0) {
      sum += parseFloat(array[0][i].f0_);
    } else {
      sum === 0;
    }
  }

  return sum;
}
almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You don't need the if/else condition at all as if there are no items in array[0], there will be no iteration.

    function quantitySum(array) {
      let sum = 0;
      for (let i = 0; i < array[0].length; i++) {
         sum += parseFloat(array[0][i].f0_);
      }
      return sum;
    }
almost 4 years ago · Santiago Trujillo Denunciar

0

You may use Array reduce function

function sum = (array) => {
    return array.reduce((accumulator, current) => accumulator += parseFloat(current.f0_)) || 0;
}
almost 4 years ago · Santiago Trujillo Denunciar

0

This is a bit extreme, but you could go with Array#reduce inside an ES6 arrow function and dramatically reduce the code

const quantitySum = array => array[0]?.reduce((b,a) => b+parseFloat(a.f0_),0) ?? 0;

let n = [[{f0_:5}, {f0_:6}]]
let o = []
console.log(quantitySum(n))
console.log(quantitySum(o))

almost 4 years ago · Santiago Trujillo 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