- 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

# Split a range of number to a specific number of intervals JavaScript

Suppose we have an interval that always starts from 0 and ends at some positive integer n, lets denote the interval with an array like this −

const interval = [0, n];

Or simply, since we know that the range will always start at 0, lets denote the interval by only the upper limit.

const interval = n;

We are required to write a JavaScript function that takes in two numbers as first and the second argument.

The first argument represents an interval starting from 0 and end at that number. And the second number determines how many equal intervals (if possible) we have to create between the actual interval.

For example: If the input arguments are 3 and 2.

Then the actual interval is [0, 3] = [0, 1, 2, 3] and we have to divide this into 2 equal intervals (if possible)

Therefore, for these inputs the output should be −

const output = [ [0, 1], [2, 3] ];

Note that the upper and lower limits of intervals are always whole numbers.

The code for this will be −

## Example

const getIntervals = (interval, num) => { const size = Math.floor(interval / num); const res = []; for (let i = 0; i <= interval; i += size) { const a = i == 0 ? i : i += 1; const b = i + size > interval ? interval : i + size; if (a < interval){ res.push([a, b]); }; }; return res; }; console.log(getIntervals(3, 2));

## Output

And the output in the console will be −

[ [0, 1], [2, 3] ]

- Related Questions & Answers
- Using activity in SAP for number range intervals and number range objects
- Squaring every digit of a number using split() in JavaScript
- Returning a range or a number that specifies the square root of a number in JavaScript
- Count number of factors of a number - JavaScript
- Armstrong number within a range in JavaScript
- Java Program to split into a number of sub-strings
- How to create a random number between a range JavaScript
- Read a specific bit of a number with Arduino
- MongoDB query to get a specific number of items
- How to find a nearest higher number from a specific set of numbers: JavaScript ?
- Digit sum upto a number of digits of a number in JavaScript
- Finding the count of numbers divisible by a number within a range using JavaScript
- Finding number of occurrences of a specific string in MySQL?
- Clear/Set a specific bit of a number in Arduino
- Program to find number of ways to split a string in Python