Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Parse array to equal intervals in JavaScript
Let's say, we are required to write a function, say parseEqualInterval() that takes in an array of Numbers of strictly two elements as the first argument and a number n as the second argument and it inserts n-1 equidistant entries between the actual two elements of the original array so that it gets divided into n equal intervals.
For example:
// if the input array is const arr = [12, 48]; // and the interval is 4 //then the output array should be: const output = [12, 21, 30, 39, 48];
This way the array got divided into 4 equal intervals. So, let's write the code for this function:
How It Works
The algorithm calculates the step size by dividing the difference between the two numbers by the interval count. Then it inserts intermediate values using the splice method.
Implementation
const parseEqualInterval = (arr, interval) => {
const [first, second] = arr;
const size = (second - first) / interval;
for(let i = 1, el = first + size; i
4 intervals: [ 12, 21, 30, 39, 48 ]
6 intervals: [ 10, 16.67, 23.33, 30, 36.67, 43.33, 50 ]
Better Implementation (Non-Mutating)
Here's a cleaner version that returns a new array instead of modifying the original:
const createEqualIntervals = (start, end, intervals) => {
const result = [start];
const step = (end - start) / intervals;
for(let i = 1; i
3 intervals: [ 0, 10, 20, 30 ]
5 intervals: [ 100, 120, 140, 160, 180, 200 ]
4 intervals: [ 12, 21, 30, 39, 48 ]
Key Points
- The step size is calculated as
(end - start) / intervals -
Math.round((value + Number.EPSILON) * 100) / 100handles floating-point precision - The original function modifies the array in-place using
splice() - Consider using a non-mutating approach for better code predictability
Conclusion
This function effectively divides a numeric range into equal intervals by calculating step sizes and inserting intermediate values. The non-mutating version is generally preferred for cleaner, more predictable code.
