문자열 리터럴의 배열을 취하는 JavaScript 함수를 작성해야 합니다. 이 함수는 배열에서 가능한 모든 문자열 조합을 생성하고 반환해야 합니다.
예를 들어 -
입력 배열이 -
인 경우const arr = ['a', 'b', 'c', 'd'];
그러면 출력은 다음과 같아야 합니다. -
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);
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"])); 출력
콘솔의 출력은 -
[ 'abcd', 'abc', 'abd', 'ab', 'acd', 'ac', 'ad', 'a', 'bcd', 'bc', 'bd', 'b', 'cd', 'c', 'd' ]