Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Split number into n length array - JavaScript
We are required to write a JavaScript function that takes in two numbers say m and n, and returns an array of size n with all the elements of the resulting array adding up to m.
Let's write the code for this function ?
Example
Following is the code ?
const len = 8;
const sum = 5;
const splitNumber = (len, sum) => {
const res = [];
for(let i = 0; i
Output
The output in the console: ?
[
0.625, 0.625,
0.625, 0.625,
0.625, 0.625,
0.625, 0.625
]
Using Integer Division with Remainder Distribution
For whole numbers, we can distribute the remainder across the first few elements:
const splitIntegerNumber = (len, sum) => {
const quotient = Math.floor(sum / len);
const remainder = sum % len;
const result = [];
for(let i = 0; i
[ 4, 3, 3 ]
[ 2, 2, 2, 1 ]
Complete Function with Validation
Here's a robust version that handles edge cases:
const splitNumber = (length, total, useIntegers = false) => {
if (length
Equal splits: [ 3, 3, 3, 3 ]
Integer splits: [ 4, 3, 3, 3 ]
Single element: [ 100 ]
Conclusion
The function splits a number into an array of specified length where elements sum to the original number. Use equal division for decimals or integer distribution with remainder handling for whole numbers.
Advertisements
