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

140
Views
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 answers
Answer question

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 Report

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