This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
131. implement _.chunk()
Here's one possible solution:
function chunk(arr, size) { if (size < 1) { return []; } const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result;}
This function first checks to make sure the size
parameter is at least 1, and returns an empty array if it's not.
It then initializes an empty array called result
, and loops through the arr
array in increments of size
. In each iteration of the loop, it uses the slice()
method to extract a "chunk" of the array from the current index up to size
elements later, and pushes that chunk onto the result
array.
Finally, it returns the result
array.