Split Into Chunks

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to split an array into smaller arrays of a specified size using JavaScript. We will use the Array.from() and Array.prototype.slice() methods to create a new array that contains the specified number of chunks. We will also learn how to handle cases where the original array cannot be split evenly.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28621{{"`Split Into Chunks`"}} javascript/data_types -.-> lab-28621{{"`Split Into Chunks`"}} javascript/arith_ops -.-> lab-28621{{"`Split Into Chunks`"}} javascript/comp_ops -.-> lab-28621{{"`Split Into Chunks`"}} end

How to Split an Array into Chunks of a Specific Size

To practice coding, open the Terminal/SSH and type node.

To split an array into smaller arrays of a specified size, follow these steps:

  1. Use Array.from() to create a new array that fits the number of chunks that will be produced.
  2. Use Array.prototype.slice() to map each element of the new array to a chunk the length of size.
  3. If the original array cannot be split evenly, the final chunk will contain the remaining elements.

Here's an example code snippet:

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

You can use this function by passing in the array you want to split and the desired size of the chunks. For example:

chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

Summary

Congratulations! You have completed the Split Into Chunks lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like