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?

3
  • The second argument to slice isn’t a length, but the end index. Commented Apr 4, 2018 at 9: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 Commented Apr 4, 2018 at 9:17
  • I know about similar SO questions, but these seemd too complicated. That way in my comment seems simplier and easier to understand Commented Apr 4, 2018 at 9:18

4 Answers 4

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

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

Comments

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

Comments

0

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.