Convert Array into Array of Subarrays 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]]
Example
Following is the code −
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
This will produce the following output on console −
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Advertisements