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'
]

Updated on: 21-Nov-2020

622 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements