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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read