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
]

Updated on: 15-Sep-2020

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements