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.

Example

Following is the code −

 Live Demo

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(); }
      return next;
   }
console.log(findNumber(arr, target));

Output

99

Updated on: 17-Apr-2021

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements