• Post category:JavaScript
  • Reading time:2 mins read

In this article, we will show you how to split an array into chunks using JavaScript. There are multiple ways to split an array into a smaller array of the specified size.

Ways to split an array into chunks

  1. Using while loop
  2. 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..!!

Leave a Reply