Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert array into array of subarrays - 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]]
Using Loop-based Approach
This method iterates through the array and builds subarrays by checking if the current subarray has reached the desired size:
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunk = arr => {
const size = 2;
const chunkedArray = [];
for (let i = 0; i
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Using slice() Method
A simpler approach uses the slice() method to extract chunks of the specified size:
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunkArray = (array, size) => {
const result = [];
for (let i = 0; i
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Using reduce() Method
A functional programming approach using reduce():
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunkWithReduce = (array, size) => {
return array.reduce((chunks, item, index) => {
const chunkIndex = Math.floor(index / size);
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = [];
}
chunks[chunkIndex].push(item);
return chunks;
}, []);
};
console.log(chunkWithReduce(arr, 2));
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Comparison
| Method | Readability | Performance | Flexibility |
|---|---|---|---|
| Loop-based | Medium | Good | High |
| slice() | High | Good | High |
| reduce() | Medium | Good | High |
Conclusion
The slice() method provides the cleanest and most readable solution for chunking arrays. All three approaches handle odd-length arrays correctly by placing remaining elements in the final subarray.
