How to generate all combinations of a string in JavaScript ? - GeeksforGeeks

12 Jan, 2022
In this article, we are going to see we can generate all the possible combinations of a given string using JavaScript methods or concepts.
You are given a string, containing different characters, you need to generate all combinations of a string by selecting a character at once and then re-arranging that character with other characters in such a way all the combinations could be generated and printed easily in our output.
There are several approaches to solve this particular problem and we will discuss each of them one by one, but let’s first of all understand what exactly we need to implement.
Following pictorial representations describes the scenario of generating all possible combinations of a given string.
Dog => Possible Combination [D], [Do], [Dog], [o], [og], [g]
As an example (mentioned in the above pictorial representation) a string named ‘”Dog” can be further split into multiple strings like “D” , “Do” and so on.
Following are the several approaches to generate all the combinations of a string in JavaScript-
Approach 1:
In this approach we will use the data structure called an array and will run two for loops on the given string which is actually the main logical part of our code
Further we will use .push() and .slice() method to add our result into an array.
Example:
Javascript
<script>let possibleCombinations = (str) =>{    let combinations = [];      for(let i = 0 ;i < str.length; i++)    {        for(let j = i + 1; j< str.length + 1; j++)        {            combinations.push(str.slice(i , j));        }    }   return combinations;}console.log(possibleCombinations('Dog'));</script>
Output: The output of the above program will be as follows.
[ 'd', 'do', 'dog', 'o', 'og', 'g' ]
Approach 2:
In this approach we will again be using an array as our result printing variable and we will take our current index value as starting value (which is 0).
Then we will run a while loop and inside that while loop we will store our character present at our current index value using .charAt() method.
Then we will declare a temporary array in which we will store that character obtained.
Then we will run a for-in loop where in we will push our result and thereafter we will add our result in the the result variable using .concat() method and we will then increment our current index variable value.
Example:
Javascript
<script>let stringCombinations = (str) => {  let strLength = str.length;  let result = [];  let currentIndex = 0;  while (currentIndex < strLength) {    let char = str.charAt(currentIndex);    let x;    let arrTemp = [char];    for (x in result) {      arrTemp.push("" + result[x] + char);    }    result = result.concat(arrTemp);    currentIndex++;  }  return result;};console.log(stringCombinations("dog"));</script>
Output: The output of the above code will be as follows.
 [ 'd', 'o', 'do', 'g', 'dg', 'og', 'dog' ]
Approach 3:
In this approach, we will use two arrays one is temporary which will initially store our results and at the end we will add our results in the second result array.
Here we will use firstly a for loop and inside that for loop we will add each character character of a string in the temporary array and then we will take starting index value as 0.
Then inside the while loop we will use .push() method to push our result into the temporary array and increment the current index value.
Then after the while loop we will add the result into our result array from the temporary array and then print the result array.
Example:
Javascript
<script>let combinations = (str) => {  let tempArr = [];  let resultArr = [];  for (let i = 0; i < str.length; i++) {    tempArr = [str[i]];    let index = 0;    while (resultArr[index]) {      tempArr.push("" + resultArr[index] + str[i]);      index++;    }    resultArr = resultArr.concat(tempArr);  }  return resultArr;};console.log(combinations("dog"));</script>
Output: The output of the above program will be.
[ 'd', 'o', 'do', 'g', 'dg', 'og', 'dog' ]
abhishek0719kadiyan
JavaScript-Questions
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript