Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for-loop with certain step

I have an array with 100 elements, I want to take an element from 10th to 15th (10, 11, 12, 13, 14, 15), than from 20th to 25th, than from 30th to 35th, from 40th to 45th and from 50th to 55th, so I always have a gap= 4 and store to a new 2D value. I found out how to store to 2D array, but how could I make this gap?

this is how I could make a chunk of size 6 (because I always need first six element of "decade")

var newArr = [];
while(arr.length) newArr.push(arr.splice(0,6));

or

function splitArray(array, part) {
    var tmp = [];
    for(var i = 0; i < array.length; i += part) {
        tmp.push(array.slice(i, i + part));
    }
    return tmp;
}

console.log(splitArray(m1, 6));

But first of all I have to make a new array of elements (10-15, 20-25 and so on...). How could I do this?

like image 746
Anna F Avatar asked Jan 20 '26 03:01

Anna F


2 Answers

Your function needs a separate parameter for the stride and the size of each part. It uses the stride when incrementing the for loop variable, and the size when taking the slice.

function splitArray(array, stride, size) {
    var tmp = [];
    for(var i = 0; i < array.length; i += stride) {
        tmp.push(array.slice(i, i + size));
    }
    return tmp;
}

var m1 = [];
for (var i = 0; i < 100; i++) {
    m1.push(i);
}
console.log(splitArray(m1, 10, 6));
like image 133
Barmar Avatar answered Jan 22 '26 17:01

Barmar


A generator function removes the need to store intermediate results. Introducing an offset argument allows you to skip the first five values 0, 1, 2, 3, 4, 5:

function* splitArray(array, stride, size, offset = 0) {
  for (let i = offset; i < array.length; i += stride) {
    yield array.slice(i, i + size);
  }
}

// Example:
const array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
console.log(...splitArray(array, 10, 6, 10));

Apart from those particularities, this implementation is identical to Barmar's answer.

like image 27
le_m Avatar answered Jan 22 '26 17:01

le_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!