3

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@AnnaF Please mark as answer if it answers your question
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.