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 < len; i++){
        res.push(sum / len);
    };
    return res;
};
console.log(splitNumber(len, sum));

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 < len; i++) {
        // Add 1 extra to first 'remainder' elements
        result.push(quotient + (i < remainder ? 1 : 0));
    }
    
    return result;
};

console.log(splitIntegerNumber(3, 10)); // [4, 3, 3]
console.log(splitIntegerNumber(4, 7));  // [2, 2, 2, 1]
[ 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 <= 0) return [];
    if (length === 1) return [total];
    
    if (useIntegers) {
        const quotient = Math.floor(total / length);
        const remainder = total % length;
        const result = [];
        
        for(let i = 0; i < length; i++) {
            result.push(quotient + (i < remainder ? 1 : 0));
        }
        return result;
    } else {
        return Array(length).fill(total / length);
    }
};

// Test with different scenarios
console.log("Equal splits:", splitNumber(4, 12));
console.log("Integer splits:", splitNumber(4, 13, true));
console.log("Single element:", splitNumber(1, 100));
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.

Updated on: 2026-03-15T23:18:59+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements