Convert an Array into Array of Subarrays using JavaScript
Last Updated :
21 Aug, 2024
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.
JavaScript
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);
OutputArray 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 .
JavaScript
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));
OutputRecursive 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.
JavaScript
function convertToSubarrays(arr) {
return arr.map(element => [element]);
}
let inputArray = [1, 2, 3, 4];
let subarrays = convertToSubarrays(inputArray);
console.log("Array of subarrays:", subarrays);
OutputArray 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.
Similar Reads
How to convert Object's array to an array using JavaScript ?
Given an array of objects and the task is to convert the object values to an array with the help of JavaScript. There are two approaches that are discussed below: Approach 1:We can use the map() method and return the values of each object which makes the array. Example: html<!DOCTYPE HTML>
2 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of ContentApproach 1: using JavaScript array.map() and toString() methodsApproach 2: Us
2 min read
JavaScript - Convert a Number into JS Array
You have a number, like 12345, and you need to convert it into an array where each element represents a digit of the number. For example, 12345 should become [1, 2, 3, 4, 5]. How can you achieve this in JavaScript?In JavaScript, there are various ways to transform a number into an array of its digit
3 min read
How to Convert an Array into a Complex Array JavaScript ?
Complex arrays can represent multiple dimensions or data with a structure. This article discusses two approaches to converting an array into a more complex array.Table of ContentUsing Multidimensional ArraysUsing Array.from()Using the reduce() MethodUsing the map() Method with slice() MethodUsing Mu
3 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to c
2 min read
Convert Array to String in JavaScript
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
7 min read
How to convert array of strings to array of numbers in JavaScript ?
Converting an array of strings to an array of numbers in JavaScript involves transforming each string element into a numerical value. This process ensures that string representations of numbers become usable for mathematical operations, improving data handling and computational accuracy in applicati
4 min read
Convert an Array to JSON in JavaScript
Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of ContentJSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While send
2 min read
Split a String into an Array of Words in JavaScript
JavaScript allows us to split the string into an array of words using string manipulation techniques, such as using regular expressions or the split method. This results in an array where each element represents a word from the original string. 1. Using split() MethodUsing split() method with a chos
5 min read
JavaScript - Convert an Array to an Object
These are the following ways to convert an array to an Object:1. Using JavaScript Object.assign() method The first approach is using the Object.assign() method. This method copies the values of all enumerable properties from source objects(one or more) to a target object.JavaScriptlet a = [1, 2, 3,
2 min read