Taking part from array of numbers by percent JavaScript

We have an array of number literals like this:

const numbers = [10,6200,20,20,350,900,26,78,888,10000,78,15000,200,1280,2000,450];

We need to write a function that takes an array of numbers and a percentage (0-100). The function should return the first n elements from the array that sum up to equal or just less than the specified percentage of the total array sum.

Understanding the Problem

Let's take a simpler example:

const numbers = [12, 10, 6, 8, 4, 2, 8];

For this array, the total sum is 50. If we provide 25 as the percentage, we need to return the first n elements that sum up to ? 25% of 50, which is 12.5. Since the first element (12) is ? 12.5, but adding the second element (10) would make it 22 > 12.5, we return only [12].

Algorithm Approach

The solution follows these steps:

  1. Calculate the total sum of the array using reduce()
  2. Calculate the target threshold: (sum × percent) / 100
  3. Iterate through elements, adding each to a running total
  4. Keep adding elements while the running total ? threshold
  5. Stop when adding the next element would exceed the threshold

Implementation

const numbers = [10,6200,20,20,350,900,26,78,888,10000,78,15000,200,1280,2000,450];

const findPercent = (arr, percent) => {
    const sum = arr.reduce((acc, val) => acc + val);
    const part = [];
    let curr = 0;
    
    for(let i = 0; i < arr.length; i++){
        curr += arr[i];
        if(curr <= (sum * percent) / 100){
            part.push(arr[i]);
        } else {
            break;
        }
    }
    return part;
};

console.log("35%:", findPercent(numbers, 35));
console.log("5%:", findPercent(numbers, 5));
console.log("65%:", findPercent(numbers, 65));
35%: [
  10, 6200, 20, 20,
  350, 900, 26, 78,
  888
]
5%: [ 10 ]
65%: [
  10, 6200, 20,
  20, 350, 900,
  26, 78, 888,
  10000, 78
]

How It Works

For the given array with sum 38,530:

  • 35%: Threshold = 13,485.5. Elements [10...888] sum to 13,492, but adding 10000 would exceed threshold
  • 5%: Threshold = 1,926.5. Only first element (10) fits
  • 65%: Threshold = 25,044.5. Elements up to second 78 sum to 24,570

Key Points

  • The function processes elements in order from the beginning of the array
  • It stops as soon as adding the next element would exceed the percentage threshold
  • The result includes all elements that can be added without exceeding the limit
  • Works with any percentage between 0 and 100

Conclusion

This approach efficiently finds the maximum number of initial array elements that sum to a specified percentage of the total. The algorithm ensures we never exceed the threshold while maximizing the number of included elements.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements