DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Algorithm 202: Array Chunking in 3 Ways

Welcome to yet another series on algorithm - Algorithm 202. We are going to focus on array manipulation.

In how many ways can you chunk an array?


chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 2) 
/* [ 
    [ 1, 2 ],
    [ 3, 4 ],
    [ 5, 6 ],
    [ 7, 8 ],
    [ 9, 10 ],
    [ 11, 12 ],
    [ 13 ] 
   ]
*/

chunkArray(["Aaran", "Aaren", "Aarez", "Aarman", "Aaron", "Aaron-James", "Aarron"], 3)
/* [ 
     [ 'Aaran', 'Aaren', 'Aarez' ],
     [ 'Aarman', 'Aaron', 'Aaron-James' ],
     [ 'Aarron' ] 
   ]
*/
Enter fullscreen mode Exit fullscreen mode

We want to look at 3 ways to achieve this.

Prerequisite

To benefit from this article, you need to have basic understanding of javascript's array methods.

Let's Chunk an Array using:

  • for...of..loop, push()
      function chunkArray(arr, limiter) {
        let finalArray = [];
        let tempArray = [];

        for (value of arr) {
          if (tempArray.length < limiter) {
            tempArray.push(value);
          } else {
            finalArray.push(tempArray);
            tempArray = [];
            tempArray.push(value);
          }
        }

        finalArray.push(tempArray);
        return finalArray;
      }
Enter fullscreen mode Exit fullscreen mode
  • for...loop, push(), slice()
      function chunkArray(arr, limiter) {
        let finalArray = [];

        for (let i = 0; i <= arr.length; i += limiter) {
          finalArray.push(arr.slice(i, i + limiter));
        }
        return finalArray;
      }
Enter fullscreen mode Exit fullscreen mode
  • for...loop, push(), splice(), if...statement
      function chunkArray(arr, limiter) {
        let finalArray = [];
        let arrayLength = arr.length;

        for (let i = 0; i <= arrayLength; i++) {
          if (arr.length != 0) {
            finalArray.push(arr.splice(0, limiter));
          }
        }
        return finalArray;
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. You can try this out with recursion or other looping construct. I will love to know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

Up Next: Algorithm 202: Array Merging Without Duplicates in 4 Ways

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Top comments (4)

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty • Edited

Recursive approach:-


<script>
 var multiDim=[];
 function chunkArray(array){
    if(array.length==0) return;
    multiDim.push(array.splice(0,3));
    chunkArray(array);
    return multiDim;
 }
 console.log(chunkArray(["Aaran", "Aaren", "Aarez", "Aarman", "Aaron", "Aaron-James", "Aarron"], 3));
</script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rusty_xx profile image
Grey_W I N D

Please I don't understand how the first code works.

Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

Grey, thank you for taking your time to read through. Here is how the first code works

function chunkArray(arr, limiter) {
  // array to hold all chunks 
  let finalArray = [];
  // temporary array to hold each chunk
  let tempArray = [];

  // loop through each value of the array
  for (value of arr) {
    // check if the temporary array length is less than the desired size (limiter)
    if (tempArray.length < limiter) {
      // add the current value to the temporary array
      tempArray.push(value);
    } else {
      // if the temporary array length is equal to the desired size (limiter), add the whole of the temporary array to the final array
      finalArray.push(tempArray);
      // empty the temporary array
      tempArray = [];
      // add the current array value at which it got filled up 
      tempArray.push(value);
    }
  }

  // after the whole looping, the last chunk (temporary array) will need one more loop to be able to be added to the final loop. Since that is not available, we add it at this point before returning the final array
  finalArray.push(tempArray);
  return finalArray;
}
chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5)

Hope you get it now?

I usually console log a value at any point of a code I don't understand. It makes it easier for me to see what is happening at each point of the code clearly

Collapse
 
rusty_xx profile image
Grey_W I N D

Thank you so much. It's clearer now