Split number into n length array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 15-Sep-2020 09:20:57
Advertisements