Chunk Array
Challenge Description
Write a function that takes an array and a chunk size as input. The function should return a new array where the original array is split into chunks of the specified size.
For example:
chunk([1, 2, 3, 4, 5], 2)
should return[[1, 2], [3, 4], [5]]
.chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)
should return[[1, 2, 3], [4, 5, 6], [7, 8]]
.
Tips to Solve
tip
- Initialize an empty array
chunked
to store the chunks. - Use a
while
loop to iterate through the original array. - Use the
slice
method to create chunks of the specified size and push them into thechunked
array. - Increment the index by the chunk size to move to the next chunk.
Step-by-Step Solution
Let's break down the solution into easy steps:
-
Initialize Variables:
- Create an empty array
chunked
to store the chunks. - Initialize an
index
variable to 0 to keep track of the current position in the original array.
const chunked = [];
let index = 0; - Create an empty array
-
Iterate Through the Array:
- Use a
while
loop to iterate through the original array. - The loop should run as long as the
index
is less than the length of the array.
while (index < array.length) {
const chunk = array.slice(index, index + size);
chunked.push(chunk);
index += size;
} - Use a
-
Slice the Array:
- Use the
slice
method to create a chunk of the specified size starting from the currentindex
. - Push the chunk into the
chunked
array.
const chunk = array.slice(index, index + size);
chunked.push(chunk); - Use the
-
Increment the Index:
- Increment the
index
by the chunk size to move to the next chunk.
index += size;
- Increment the
-
Return the Chunked Array:
- After the loop completes, return the
chunked
array.
return chunked;
- After the loop completes, return the
Full Solution Code
Here is the complete solution using the steps above:
const chunk = (array, size) => {
const chunked = [];
let index = 0;
while (index < array.length) {
const chunk = array.slice(index, index + size);
chunked.push(chunk);
index += size;
}
return chunked;
};
console.log(chunk([1, 2, 3, 4, 5], 2)); // Output: [[1, 2], [3, 4], [5]]
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]