如何使用JavaScript从3个数组各取一项生成新数组?
如何用JavaScript从多个数组中各取一个元素生成所有组合数组
需求说明
给定多个数组,需要从每个数组中选取一个元素,生成所有可能的组合数组(即笛卡尔积)。比如:
- 输入数组:
const array1 = ['Male', 'Female']; const array2 = ['18-20']; const array3 = ['Self Employed', 'Part Time', 'Full Time']; - 期望输出所有6种组合数组。
方法一:嵌套循环(适合固定数量的数组)
如果数组数量固定(比如3个),可以直接用嵌套循环遍历每个数组的元素,组合成新数组:
const array1 = ['Male', 'Female']; const array2 = ['18-20']; const array3 = ['Self Employed', 'Part Time', 'Full Time']; const combinations = []; // 遍历每个数组的元素,组合所有可能 for (const gender of array1) { for (const age of array2) { for (const job of array3) { combinations.push([gender, age, job]); } } } // 打印结果 combinations.forEach((arr, idx) => { console.log(`${idx + 1}th Array:- [${arr.join(', ')}];`); });
运行后会输出和示例完全一致的结果,这种写法直观易懂,适合数组数量明确的场景。
方法二:通用笛卡尔积函数(支持任意数量数组)
如果需要处理不确定数量的数组,可以写一个通用函数来计算笛卡尔积:
// 生成多个数组的笛卡尔积 function getCartesianProduct(...arrays) { return arrays.reduce((acc, currentArray) => { // 把已有组合和当前数组的每个元素拼接 return acc.flatMap(combination => currentArray.map(item => [...combination, item]) ); }, [[]]); // 初始值为空数组的数组,用于第一次拼接 } // 使用示例 const array1 = ['Male', 'Female']; const array2 = ['18-20']; const array3 = ['Self Employed', 'Part Time', 'Full Time']; const combinations = getCartesianProduct(array1, array2, array3); // 打印结果 combinations.forEach((arr, idx) => { console.log(`${idx + 1}th Array:- [${arr.join(', ')}];`); });
这个函数利用reduce和flatMap来逐步构建所有组合,不管输入多少个数组都能适用,扩展性更强。
内容的提问来源于stack exchange,提问作者user6885623
相关产品推荐
相关产品推荐

