Finding sum of remaining numbers to reach target average using JavaScript

Problem

We are required to write a JavaScript function that takes in an array of numbers and a single number.

Our function should find that very number which should be pushed to the array so that its average equals the number specified by the second argument.

Understanding the Formula

To find the number that makes the average equal to the target, we use this mathematical approach:

  • Current sum of array elements
  • New array length will be (current length + 1)
  • Required total sum = target × new array length
  • Number to add = required total sum - current sum

Example

Following is the code −

const arr = [4, 20, 25, 17, 9, 11, 15];
const target = 25;

function findNumber(arr, target) {
    let sum = arr.reduce((a, b) => a + b, 0);
    let avg = sum / arr.length;
    let next = Math.ceil((target * (arr.length + 1)) - sum);
    if (next <= 0) { 
        throw new Error('Cannot achieve target average'); 
    }
    return next;
}

console.log(findNumber(arr, target));

Output

99

Step-by-Step Breakdown

Let's trace through the calculation:

const arr = [4, 20, 25, 17, 9, 11, 15];
const target = 25;

function findNumberDetailed(arr, target) {
    let sum = arr.reduce((a, b) => a + b, 0);
    console.log("Current sum:", sum);
    
    let currentAvg = sum / arr.length;
    console.log("Current average:", currentAvg);
    
    let newLength = arr.length + 1;
    console.log("New array length:", newLength);
    
    let requiredSum = target * newLength;
    console.log("Required total sum:", requiredSum);
    
    let numberToAdd = requiredSum - sum;
    console.log("Number to add:", numberToAdd);
    
    return Math.ceil(numberToAdd);
}

console.log("Result:", findNumberDetailed(arr, target));
Current sum: 101
Current average: 14.428571428571429
New array length: 8
Required total sum: 200
Number to add: 99
Result: 99

Handling Edge Cases

The function includes error handling for cases where the target average is impossible to achieve:

function findNumberSafe(arr, target) {
    if (arr.length === 0) {
        throw new Error('Array cannot be empty');
    }
    
    let sum = arr.reduce((a, b) => a + b, 0);
    let numberToAdd = (target * (arr.length + 1)) - sum;
    
    if (numberToAdd <= 0) {
        throw new Error('Target average too low - cannot be achieved');
    }
    
    return Math.ceil(numberToAdd);
}

// Test with different scenarios
try {
    console.log(findNumberSafe([10, 20, 30], 5)); // This will throw an error
} catch (error) {
    console.log("Error:", error.message);
}

console.log(findNumberSafe([1, 2, 3], 10)); // This will work
Error: Target average too low - cannot be achieved
31

Conclusion

This function calculates the exact number needed to achieve a target average by using the mathematical relationship between sum, count, and average. The Math.ceil() ensures we get an integer result when dealing with decimal calculations.

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

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements