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"];
Example
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);
p.push(arr[i]);
result = result.concat(combine(p, i + 1));
result.push(p.join(''));
};
return result;
}
return combine([], 0);
};
console.log(getCombinations(["a", "b", "c", "d"]));Output
And the output in the console will be −
[ 'abcd', 'abc', 'abd', 'ab', 'acd', 'ac', 'ad', 'a', 'bcd', 'bc', 'bd', 'b', 'cd', 'c', 'd' ]