admin管理员组

文章数量:1415137

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?

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?

Share Improve this question edited Jun 22, 2017 at 22:41 kk. 3,97512 gold badges39 silver badges71 bronze badges asked Jun 22, 2017 at 22:08 Anna FAnna F 1,6834 gold badges25 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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));

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.

本文标签: arraysJavascript forloop with certain stepStack Overflow