1

Input:

["A", "B", "C"]

Expected output:

["A", "B", "C", "A, B", "A, C", "B, C", "A, B, C"]

This is a simple example case, but the function should work for strings and arrays of all lengths. Strings may have certain letters repeated, e.g. "AABB", which is distinct from "A" and "B". Order by number of elements first then alphanumerical sort is desired but not required for this solution.

3 Answers3

1

You can use a permutation function, and then join certain strings after spliting them:

const arr = ["A", "B", "C"];

function getCombinations(chars) {
  var result = [];
  var f = function(prefix, chars) {
    for (var i = 0; i < chars.length; i++) {
      result.push(prefix + chars[i]);
      f(prefix + chars[i], chars.slice(i + 1));
    }
  }
  f('', chars);
  return result;
}

const permutations = getCombinations(arr).map(e => e.length > 1 ? e.split("").join(", ") : e);

console.log(permutations);

Permutations function from this answer.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Clarified my question a bit, as this appears to be unable to distinguish between strings greater than single letter length. –  Mar 14 '19 at 02:22
1

This is actually something I have been working on in scheme lately, what you appear to be looking for is a procedure that generates a power set from a set input. There just happens to be a recursive algorithm that already exists to solve this problem, but it is based on math that I don't need to go into here.

Here is a simple JavaScript implementation from another post here that I modified for your problem:

const myList = ["A", "B", "C"];
const powerSet = 
      theArray => theArray.reduce(
        (subsets, value) => subsets.concat(
         subsets.map(set => [value,...set])
        ),
        [[]]
      );

console.log(powerSet(myList));
Jodast
  • 1,279
  • 2
  • 18
  • 33
0

This is what I ended up using as a basis for my implementation:

https://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php