
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Questions & Answers
- Finding lunar sum of Numbers - JavaScript
- Finding average age from array of Objects using JavaScript
- Creating permutations to reach a target number, but reuse the provided numbers JavaScript
- Finding pandigital numbers using JavaScript
- Finding average word length of sentences - JavaScript
- Finding sum of all numbers within a range in JavaScript
- Finding closest pair sum of numbers to a given number in JavaScript
- Finding two numbers given their sum and Highest Common Factor using JavaScript
- Finding the sum of all numbers in the nth row of an increasing triangle using JavaScript
- Finding two numbers that produce equal to the sum of rest in JavaScript
- Finding sum of multiples in JavaScript
- Finding special type of numbers - JavaScript
- Greatest sum of average of partitions in JavaScript
- Find possible numbers in array that can sum to a target value JavaScript
- Finding tidy numbers - JavaScript
Advertisements