
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate all combinations of supplied words in JavaScript
We are required to write a JavaScript function that takes in an array of strings. The function should then generate and return all possible combinations of the strings of the array.
Example
The code for this will be −
const arr = ['a', 'b', 'c', 'd']; const permutations = (len, val, existing) => { if(len==0){ res.push(val); return; } for(let i=0; i<arr.length; i++){ // so that we do not repeat the item, using an array here makes it O(1) operation if(!existing[i]){ existing[i] = true; permutations(len−1, val+arr[i], existing); existing[i] = false; } } } let res = []; const buildPermuations = (arr = []) => { for(let i=0; i < arr.length; i++){ permutations(arr.length−i, "", []); } }; buildPermuations(arr); console.log(res);
Example
And the output in the console will be −
[ 'abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'a', 'b', 'c', 'd' ]
- Related Questions & Answers
- All combinations of sums for array in JavaScript
- Python - Generate all possible permutations of words in a Sentence
- C++ Program to Generate All Possible Combinations of a Given List of Numbers
- Generate all combinations of a specific size from a single set in PHP
- Reverse all the words of sentence JavaScript
- How to get all combinations of some arrays in JavaScript?
- Find all substrings combinations within arrays in JavaScript
- C++ Program to Generate All Possible Combinations Out of a,b,c,d,e
- JavaScript function that generates all possible combinations of a string
- Algorithm to get the combinations of all items in array JavaScript
- Print all combinations of factors in C++
- Finding all possible combinations from an array in JavaScript
- Print all combinations of balanced parentheses in C++
- All pair combinations of 2 tuples in Python
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
Advertisements