Split an array into chunks in JavaScript
In this article, we will show you how to split an array into chunks in JavaScript. There are multiple ways to split an array into a smaller array of the specified size.
Checkout more articles on JavaScript
Ways to split an array into chunks
1. Using while loop
Let’s use the following code to split an array into chunks using the while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10']; const chunkSize = 3; const chunkList = []; while (list.length) { chunkList.push(list.splice(0, chunkSize)); } console.log(chunkList); // [ // ['Item 1', 'Item 2', 'Item 3'], // ['Item 4', 'Item 5', 'Item 6'], // ['Item 7', 'Item 8', 'Item 9'], // ['Item 10'] // ]; |
2. Using lodash function
Now, we will show you another option to get the chunks using the lodash chunks method.
1 2 3 4 5 6 7 8 9 10 | const list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10']; const chunkSize = 3; const chunkList = _.chunk(list, chunkSize); console.log(chunkList); // [ // ['Item 1', 'Item 2', 'Item 3'], // ['Item 4', 'Item 5', 'Item 6'], // ['Item 7', 'Item 8', 'Item 9'], // ['Item 10'] // ]; |
Check out this link for lodash installation.
That’s it for today.
Thank you for reading. Happy Coding..!! đŸ™‚