Alex Alex - 3 years ago 159
Javascript Question

Parse array to equal intervals JS

I want to parse my array to 4 equal intervals. For example, array [12, 48] parse to 4 intervals [12,21], [21, 30], [30, 39], [39, 48]. I could only parse my Array to pairs (code here). But I don't know how to do what I want.

var arrayTest = [];
for (var i = 0; i < 1000; i++) arrayTest[i] = i;
var ab = [2, 6];
start = ab[0];
finish = ab[1];
var ab_new = [];

for (var i = start; i <= finish; i++) ab_new[i]= arrayTest[i];
var output = [];
for (var i = start; i < ab_new.length - 1; ++i) {
output[i] = [];
output[i].push(ab_new[i]);
output[i].push(ab_new[i + 1]);
}
console.log(output);


My output is:

[ , , [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ] ]

Answer Source

You can calculate the interval and use it to map in an array of length 4 over the index.

const ab = [12, 48]

const start = ab[0];
const end = ab[1];
const interval = (end - start) / 4;

const out = Array(4)
  .fill()
  .map((_, i) => [start + i*interval, start + (i + 1) * interval])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download