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

137
Vistas
The elegant way to resolve negative zero in Javascript

I have to multiply the sign of all elements in an array.

For example 1:

input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1

Ex2:

input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1

Ex3:

input: [1, -2, 3, 0]
output: 0
Explain: 1 * (-1) * 1 * 0 = 0

And here is my solution

function cal(A)
{
    return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
}

However, the output of ex3 cal([1, -2, 3, 0]) is -0.

I've already thought about adding one more condition like this

function cal(A)
{
    var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
    if(total === 0)
        return 0;
    else
        return total;
}

And obviously, It looks ugly. Is there a more elegant way to resolve that?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In order to avoid conditional checks and keep the function purely computational you can use the curious rules of -0 to simply add 0 to the result of your reduce() which will have no effect on non-zero results but will have the effect of converting -0 to 0.

function cal(arr) {
  return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
}

console.log(cal([1, 2, 3]));     // 1
console.log(cal([1, -2, 3]));    // -1
console.log(cal([1, -2, 3, 0])); // 0

See signed zero for more general discussion.

about 4 years ago · Juan Pablo Isaza Denunciar

0

In your example, there is no need to multiply all the values. If there is at least one zero, the result is zero, so there is no need to iterate through the entire array. Example below:

function compute(arr)
{
    let result = true;
    for (let item of arr) {
        if (item === 0) return 0;
        if (item < 0) result = !result;
    }
    return result ? 1 : -1;
}

console.log(compute([1, 2, 3]));
console.log(compute([1, -2, 3]));
console.log(compute([1, -2, 3, 0]));

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