Chunking arrays in JavaScript

We are required to write a JavaScript function that takes in an array of literals and returns a new array that have elements of the original array chunked into subarrays of length exactly 2. Now if the length of original array is not exactly divisible by 2, then the last subarray should have only one element.

For example: If the input array is −

const arr = [1, 2, 3, 4, 5, 6, 7];

Then the output should be −

const output = [[1, 2], [3, 4], [5, 6], [7]]

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [1, 2, 3, 4, 5, 6, 7];
const chunk = arr => {
const size = 2;
const chunkedArray = [];
for (let i = 0; i < arr.length; i++) {
const last = chunkedArray[chunkedArray.length - 1];
if(!last || last.length === size){
chunkedArray.push([arr[i]]);
}else{
last.push(arr[i]);
}
};
return chunkedArray;
};
console.log(chunk(arr));

Output

The output in the console will be −

[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]