1

Seemed as a simple task, but doesn't work. I have an array of known length (say 9) and a chunk size (say 3). Array is always dividable by that chunk, no need to test. At first tried:

const chunked = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let i=0; i<3; i++) { 
    chunked[i] = arr.slice(i*3, 3);
}

console.log(chunked);

But then realised that slice() probably overwrites its input, so:

const chunked = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let i=0; i<3; i++) { 
    let temp = arr.slice();
    chunked[i] = temp.slice(i*3, 3);
}

console.log(chunked);

But still only first chunk is being created... Where is my error?

buzz
  • 9
  • 3
  • The second argument to `slice` isn’t a length, but the end index. – Sebastian Simon Apr 04 '18 at 09:15
  • Oh yes, wasnt aware of that. This works `for(let i=0; i<3; i++) { let temp = res.slice(); res2[i] = temp.slice(i*3, (i+1)*3); }` Many thanks – buzz Apr 04 '18 at 09:17
  • I know about similar SO questions, but these seemd too complicated. That way in my comment seems simplier and easier to understand – buzz Apr 04 '18 at 09:18

4 Answers4

2

Try following

const chunked = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let i=0; i<3; i++) { 
    let temp = arr.slice();
    
    chunked[i] = temp.slice(i*3, (i+1)*3); // Need to set appropriate begin and end
}

console.log(chunked);

For reference, Array.slice

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

arr.slice([begin[, end]])

You can loop from 0 until the length of array and increment by chunck size.

like:

const chunked = [];
const chuckSize = 3;
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for (let i = 0; i < arr.length; i += chuckSize) {
  chunked.push(arr.slice(i, i + chuckSize));
}

console.log(chunked);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

The second parameter for slice is the end index (not the length) as you may be assuming. You can find the docs here

Kenny Alvizuris
  • 435
  • 4
  • 6
0

The function slice takes parameter as slice(firstIndex, lastIndex + 1)

Please use the following code:

 const chunked = [];
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    for(let i=0; i<3; i++) { 
        chunked[i] = arr.slice(i*3, i*3 + 3);
    }
    
    console.log(chunked);
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29