- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Splitting a string into parts in JavaScript
- Splitting a string into maximum parts in JavaScript
- Splitting Number into k length array in JavaScript
- Splitting string into groups – JavaScript
- Splitting last n digits of each value in the array in JavaScript
- Divide a string into n equal parts - JavaScript
- Splitting an array into chunks in JavaScript
- Splitting an array into groups in JavaScript
- Program to find maximum score by splitting binary strings into two parts in Python
- Splitting an object into an array of objects in JavaScript
- Splitting number to contain continuous odd or even number using JavaScript
- Split number into n length array - JavaScript
- Split string into equal parts JavaScript
- Two astronauts are floating close to each other in space. Can they talk to each other without using any special device? Give reasons.
- Splitting array of numbers into two arrays with same average in JavaScript

Advertisements