Open In App

Convert an Array into Array of Subarrays using JavaScript

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.


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 .


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

Using Array.prototype.map() Method

The map() method in JavaScript creates a new array by applying a function to each element of the original array. In this approach, we use the map() method to wrap each element of the array into a subarray.

Example: In this example the convertToSubarrays function converts each element of the input array into a subarray. It uses map to create a new array of 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 the creation of a new array containing the subarrays.


Next Article
Article Tags :

Similar Reads