Algorithm to get the combinations of all items in array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of string literals. The function should generate and return all possible combinations of the strings in the array.

For example −

If the input array is −

const arr = ['a', 'b', 'c', 'd'];

Then the output should be −

const output = ["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"];


const getCombinations = (arr = []) => {
   const combine = (sub, ind) => {
      let result = []
      let i, l, p;
      for (i = ind, l = arr.length; i < l; i++) {
         p = sub.slice(0);
         result = result.concat(combine(p, i + 1));
      return result;
   return combine([], 0);
console.log(getCombinations(["a", "b", "c", "d"]));


And the output in the console will be −

   'abcd', 'abc', 'abd',
   'ab', 'acd', 'ac',
   'ad', 'a', 'bcd',
   'bc', 'bd', 'b',
   'cd', 'c', 'd'
Published on 25-Nov-2020 05:56:10