สมมติว่าเรามีตัวอักษรสองตัวแบบนี้ -
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' ]