- 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

# Non-negative set subtraction in JavaScript

We have a set of integers, and a value that we need to subtract from the sum of the set.

Like here,

[4, 5, 6, 7, 8] − 25

If we subtract from every number evenly, we'd get −

[−1, 0, 1, 2, 3]

However, we don't want any numbers less than 0.

Therefore, if we were writing an algorithm to do this, the negative numbers would overflow equally into the remaining numbers, and we'd now have −

[0, 0, 1, 2, 3] − 1

Making the resulting set −

[0, 0, 1 − 0.333, 2 − 0.333, 3 − 0.333]

Note that this is exactly the outcome we want.

All of the negative values overflow EVENLY into the remaining positive values.

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a sum number as the second argument.

The function should then compute the evenly subtracted and distributed array and return it.

## Example

The code for this will be −

const arr = [4, 5, 6, 7, 8]; const subtract = (arr, sum) => { return arr.map((el, index, array) => { const rem = array.length − index const avg = sum / rem; const toSubtract = Math.min(avg, el); sum −= toSubtract; return el − toSubtract; }); }; console.log(subtract(arr, 25));

## Output

And the output in the console will be −

[ 0, 0, 0.666666666666667, 1.666666666666666, 2.666666666666666 ]

- Related Questions & Answers
- Finding the longest non-negative sum sequence using JavaScript
- Performing the subtraction operation without the subtraction operator in JavaScript
- Non-negative Integers without Consecutive Ones in C++
- What is Subtraction Operator (-) in JavaScript?
- Finding square root of a non-negative number without using Math.sqrt() JavaScript
- JavaScript subtraction of two float values?
- Sum a negative number (negative and positive digits) - JavaScript
- Number of non-negative integral solutions of sum equation in C++
- Program to find maximum non negative product in a matrix in Python
- What is negative infinity in javascript?
- Negative number digit sum in JavaScript
- Make array numbers negative JavaScript
- How to set line breaking rules for non-CJK scripts in JavaScript?
- Set negative action to the Bootstrap 4 card
- Return the non-negative square-root of an array element-wise in Numpy