Positive, negative and zeroes contribution of an array in JavaScript

In JavaScript, you may need to analyze an array of integers to find the fractional ratio of positive, negative, and zero values. This is useful for statistical analysis and data processing tasks.

Problem Statement

Given an array of integers containing positive, negative, and zero values:

const arr = [23, -1, 0, 11, 18];

We need to write a function that calculates the fractional ratio for each group: negative, zero, and positive numbers. The output should be an array of three decimal values representing these ratios.

For the above array with length 5, the expected output is:

[0.2, 0.2, 0.6]

This represents: 20% negative (1 out of 5), 20% zero (1 out of 5), and 60% positive (3 out of 5).

Solution

const arr = [23, -1, 0, 11, 18];

const findRatio = (arr = []) => {
    const { length } = arr;
    const res = [0, 0, 0]; // [negative, zero, positive]
    
    for (let i = 0; i  el / length);
};

console.log(findRatio(arr));
[ 0.2, 0.2, 0.6 ]

How It Works

The algorithm uses a clever mathematical approach:

  • For negative numbers: el / Math.abs(el) = -1, so key + 1 = 0 (index 0)
  • For zero: 0 / Math.abs(0 || 1) = 0, so key + 1 = 1 (index 1)
  • For positive numbers: el / Math.abs(el) = 1, so key + 1 = 2 (index 2)

Alternative Approach

Here's a more straightforward implementation:

const arr2 = [5, -3, 0, -2, 8, 0, 1];

const findRatioSimple = (arr = []) => {
    const length = arr.length;
    let negative = 0, zero = 0, positive = 0;
    
    for (let num of arr) {
        if (num 

[ 0.2857142857142857, 0.2857142857142857, 0.42857142857142855 ]

Verification

You can verify the results by checking if the sum of ratios equals 1:

const ratios = findRatio([23, -1, 0, 11, 18]);
const sum = ratios.reduce((acc, val) => acc + val, 0);

console.log("Ratios:", ratios);
console.log("Sum:", sum);
console.log("Valid result:", Math.abs(sum - 1) 

Ratios: [ 0.2, 0.2, 0.6 ]
Sum: 1
Valid result: true

Conclusion

Both approaches effectively calculate the fractional ratios of negative, zero, and positive numbers in an array. The mathematical approach is more concise, while the straightforward method is more readable and easier to understand.

Updated on: 2026-03-15T23:19:00+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements