You are currently viewing How to generate all subarrays in javascript in 2022?

How to generate all subarrays in javascript in 2022?

  • Post author:
  • Post category:DSA

Hello Readers,

Interviewers like to ask questions about the subarrays as it gives a clear indication of the logical thinking and aptitude of a candidate.

Considering the above, we are going to start a new tag MCAIQ (most commonly asked interview questions) that will contain the most frequently asked questions in the interview. This will be your single stop for all such questions and interview preparations.

we will see how to generate all the subarrays of an array in javascript using iterative and recursive ways both.

Generate all subarrays using iteration

Problem Statement

Given an array, generate all the possible subarrays of the given array using an iterative way.

Examples:

				
					Input : [1, 2, 3]

Output: [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]

Input: [1, 2]

Output: [1], [1, 2], [2]
				
			

Implementation

Output

You can check the code running at jsbin link

Subarrays using iterative way

Generate all subarrays using recursion

Implementation

Output

subarrays with recursion

I hope you have learned something if you like the article please disable the adblocker if it’s enabled. This site is run by ads and it is required for it to be alive and grow.

Read the following articles – 

  1. Learn Nginx in-depth
  2. Implement binary tree using javascript

This is all for today. Please visit our other articles, and keep learning.

Please share the articles on –

Facebook
Twitter
LinkedIn
Subscribe

The latest tips and news from the industry straight to your inbox!

Join 30,000+ subscribers for exclusive access to our monthly news and tutorials!