Convert an Array into Array of Subarrays using JavaScript
Given an array Num, our task is to convert it into an array of subarrays. Each subarray should contain a single element from the original array. we are going to discuss different approaches for solving this problem.
Example:
Input: Num=[1, 2, 3, 4]
Output:[[1], [2], [3], [4]]
Below are the approaches to convert the array into an array of subarrays:
Table of Content
- Using Iterative Approach
- Using Recursive Approach
Using Iterative Approach
In this approach, we use a simple loop to iterate through each element of the array and pushes each element wrapped in a subarray to a new array.
Example: The below code example shows the usage Iterative approach to convert array into array of subarrays.
function fun(array) {
// Initialize an empty array
// to store the subarrays
let result = [];
// Iterate through each
// element in the input array
for (let i = 0; i < array.length; i++) {
// Wrap each element in a subarray and
// push it to the result array
result.push([array[i]]);
}
return result;
}
// Example usage:
let inputArray = [1, 2, 3, 4];
let subarrays = fun(inputArray);
console.log("Array of subarrays:", subarrays);
Output
Array of subarrays: [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]
Time complexity: O(n), where n is the number of elements in the array.
Space complexity: O(n), due to creating a new array with the same number of elements.
Using Recursive Approach
In this approach, we use recursion to convert array into array of subarrays. We take the base case as the input array being empty. In each recursive call, we take the first element of the array, wrap it in a subarray, and concatenate it with the result of the recursive call on the rest of the array.
Example: The below code example shows the usage Recursive approach to convert array into array of subarrays .
function fun(arr) {
// Base case: if the array is empty,
// return an empty array
if (arr.length === 0) {
return [];
}
// Recursively process the rest of the array
return [[arr[0]]].concat(fun(arr.slice(1)));
}
const input = [1, 2, 3, 4];
console.log("Recursive Output:", fun(input));
Output
Recursive Output: [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]
Time Complexity: O(n), where n is the number of elements in the array.
Space complexity: O(n), as each recursive call creates a new subarray