Open In App

How to generate all combinations of a string in JavaScript ?

We are going to see if 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.

Example:

Dog => Possible Combination [D], [Do], [Dog], [o], [og], [g]

Following are the several approaches to generate all the combinations of a string in JavaScript:



Approach 1: Use .push() and .slice() method

Example: This example shows the use of the above-explained approach.






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'));

Output
[ 'D', 'Do', 'Dog', 'o', 'og', 'g' ]

Approach 2: Using the .charAt() and .concat() method

Example: This example shows the use of the above-explained approach.




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"));

Output
[
  'd',   'o',
  'do',  'g',
  'dg',  'og',
  'dog'
]

Approach 3: Using for loop and .push() method

Example: In this example, we are using for loop and .push() method




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"));

Output
[
  'd',   'o',
  'do',  'g',
  'dg',  'og',
  'dog'
]

Article Tags :