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 −
Example
const arr = [12, 48]; const parseEqualInterval = (arr, interval) => { const [first, second] = arr; const size = (second-first) / interval; for(let i = 1, el = first+size; i < interval; i++, el += size){ arr.splice(i, 0, Math.round((el + Number.EPSILON) * 100) / 100); }; }; parseEqualInterval(arr, 4); console.log(arr); parseEqualInterval(arr, 6); console.log(arr); parseEqualInterval(arr, 10); console.log(arr); parseEqualInterval(arr, 15); console.log(arr);
Output
The output in the console will be −
[ 12, 21, 30, 39, 48 ] [ 12, 13.5, 15, 16.5, 18, 19.5, 21, 30, 39, 48 ] [ 12, 12.15, 12.3, 12.45, 12.6, 12.75, 12.9, 13.05, 13.2, 13.35, 13.5, 15, 16.5, 18, 19.5, 21, 30, 39, 48 ] [ 12, 12.01, 12.02, 12.03, 12.04, 12.05, 12.06, 12.07, 12.08, 12.09, 12.1, 12.11, 12.12, 12.13, 12.14, 12.15, 12.3, 12.45, 12.6, 12.75, 12.9, 13.05, 13.2, 13.35, 13.5, 15, 16.5, 18, 19.5, 21, 30, 39, 48 ]