다음과 같은 두 개의 리터럴 배열이 있다고 가정합니다. -
const arr1= ['a', 'b', 'c']; const arr2= ['d', 'e', 'f'];
우리는 이러한 두 개의 배열을 취하고 배열에서 가능한 모든 조합을 만드는 JavaScript 함수를 작성해야 합니다.
따라서 이 두 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [ad, ae, af, bd, be, bf, cd, ce, cf];
예시
이에 대한 코드는 -
const arr1= ['a', 'b', 'c'];
const arr2= ['d', 'e', 'f'];
const combineArrays = (...arr) => {
const res = [];
const combinePart = (part, index) => {
arr[index].forEach(el => {
const p = part.concat(el);
if(p.length === arr.length){
res.push(p.join(''));
return;
};
combinePart(p, index + 1);
});
};
combinePart([], 0);
return res;
}
console.log(combineArrays(arr1, arr2)); 출력
콘솔의 출력은 -
[ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]