Split an array into chunks in JavaScript
📅August 17, 2021
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
- string-contains-a-valid-vimeo-url-using-javascript" title="Check if the string contains a valid Vimeo URL using JavaScript">Check if the string contains a valid Vimeo URL using JavaScript
- Check if an array contains all the elements of another array in JavaScript
- Methods of Promises in JavaScript
- number-in-javascript" title="Remove the leading zero from a number in JavaScript">Remove the leading zero from a number in JavaScript
- Truncate string and add ellipsis in JavaScript
Ways to split an array into chunks
- Using while loop
- lodash function">Using lodash function
1. Using while loop
Let’s use the following code to split an array into chunks using the while loop.
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.
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..!! 🙂