Splitting Number into k length array in JavaScript


We are required to write a JavaScript function that takes in two numbers say m and k, and returns an array of size k with all the elements of the resulting array adding up to m.

Example

The code for this will be −

const len = 30;
const sum = 121;
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 −

[
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333,
   4.033333333333333, 4.033333333333333
]

Updated on: 15-Oct-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements