Chop array into chunks of given length

Write a function to chop an array into chunks of a given length and return each chunk as an array.

Example

Input:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3

Output:
[[1,2,3], [4,5,6], [7,8,9], [10]]

Please note, the input array should not be modified.

We are going to see the two different implementations of this,

1. A simple function that will take the input and return the output.
2. We will extend the JavaScript array and add a new method chop, which will do the same.


Normal function.

We will traverse till there is an element in the array, in each iteration slice the sub-array of the given size and push them to the output array.

const chop = (arr, size = arr.length) => {
    //temp array
    const temp = [...arr];
  
    //output
    const output = [];
    let i = 0;
    
    //iterate the array
    while (i < temp.length) {
        //slice the sub-array of given size
        //and push them in output array
        output.push(temp.slice(i, i + size));
        i = i + size;
    }
  
    return output;
}
Input:
console.log(chop([1,2,3,4,5,6,7,8,9,10], 3));

Output:
[[1,2,3], [4,5,6], [7,8,9], [10]]

Adding a new method to the array by extending it.

We can use the same logic and add a new method to the array by extending its prototype.

Deep copy all the elements of the array and if the size is not defined then return this deep copy, else return the array of chunks.

Array.prototype.chop = function(size){
    //temp array
    const temp = [...this];
    
    //if size is not defined
    if(!size){
      return temp;
    }  
  
    //output
    const output = [];
    let i = 0;
    
    //iterate the array
    while (i < temp.length) {
        //slice the sub-array of given size
        //and push them in output array
        output.push(temp.slice(i, i + size));
        i = i + size;
    }
  
    return output;
}
Input:
const arr = [1,2,3,4,5,6,7,8,9,10];
const output = arr.chop(3);
console.log(output);

Output:
[[1,2,3], [4,5,6], [7,8,9], [10]]