

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting number into n parts close to each other in JavaScript
Problem
We are required to write a JavaScript function that takes in a number, num, as the first argument and another number, parts, as the second argument.
Our function should split the number num into exactly (parts) numbers and we should keep these two conditions in mind −
- The numbers should be as close as possible
- The numbers should even (if possible).
And the ordering of numbers is not important.
For example, if the input to the function is −
Input
const num = 20; const parts = 6;
Output
const output = [3, 3, 3, 3, 4, 4];
Example
Following is the code −
const num = 20; const parts = 6; const splitNumber = (num = 1, parts = 1) => { let n = Math.floor(num / parts); const arr = []; for (let i = 0; i < parts; i++){ arr.push(n) }; if(arr.reduce((a, b)=> a + b,0) === num){ return arr; }; for(let i = 0; i < parts; i++){ arr[i]++; if(arr.reduce((a, b) => a + b, 0) === num){ return arr; }; }; }; console.log(splitNumber(num, parts));
Output
[ 4, 4, 3, 3, 3, 3 ]
- Related Questions & Answers
- Splitting a string into parts in JavaScript
- Splitting a string into maximum parts in JavaScript
- Splitting Number into k length array in JavaScript
- Divide a string into n equal parts - JavaScript
- Splitting last n digits of each value in the array in JavaScript
- Splitting string into groups – JavaScript
- Program to find maximum score by splitting binary strings into two parts in Python
- Splitting an array into groups in JavaScript
- Splitting an array into chunks in JavaScript
- Split string into equal parts JavaScript
- Split number into n length array - JavaScript
- Break Number Into 3 parts to find max sum
- C++ Partition a Number into Two Divisible Parts
- Divide a number into two parts in C++ Program
- Splitting an object into an array of objects in JavaScript
Advertisements