TypeScript / JavaScript: Create Array Chunks from Given Array

Often we need to process the array in batches rather than processing whole of the array at once. For that purpose we may need to split the array in chunks of a specified size.

Let’s see how we can split the array in chunks of a specified chunk size.

Consider the following array.

const given = [3, 4, 5, 2, 6, 3, 2, 25, 5, 2, 45, 7, 4, 3];

and we want to split this array into chunks of chunk_size = 3

const given = [3, 4, 5, 2, 6, 3, 2, 25, 5, 2, 45, 7, 4, 3];
const chunk_size = 3;

const chunks = Array.from({ length: Math.ceil(given.length / chunk_size) }).map(() => given.splice(0, chunk_size));

console.table(chunks);

Output

Array.from()

Array.from() method creates array of length defined by the length property.

const arr = Array.from({length:3});
console.table(arr);

Output

Array.prototype.map()

map method can be used to transform each element of the array.

It returns a new array of elements applied the specified function.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Array.prototype.splice()

splice(start, deleteCount)

splice method can remove the number of elements from the start position and returns the deleted elements.

const months = ['Jan', 'March', 'April', 'June'];
const deletedmonths = months.splice(1, 1);

console.log('Remaining months');
console.table(months);
console.log('Deleted months');
console.table(deletedmonths);

Output

References:

Array.from()

Array.prototype.map()

Array.prototype.splice()

Conclusion

In this post we learned how we can create the chunks of array of a specified length from the given array.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s