JS算法实现:双数组匹配统计特定性别年龄群体数量
最优实现:按性别统计符合年龄条件的人数
针对你的需求——匹配性别与年龄数组,统计某性别中年龄超特定值、另一性别中年龄低于特定值的人数,下面给出几种实现方式及优劣分析:
一、直接计数(推荐:效率最高)
直接遍历数组,通过累加变量统计符合条件的人数,不需要额外存储数组,兼顾时间与空间效率。
代码示例:
const gender = ["man","woman","man","man","woman"]; const age = [30,20,13,63,9]; // 初始化统计变量 let maleOver18 = 0; let femaleUnder18 = 0; // 一次遍历完成统计 for (let i = 0; i < gender.length; i++) { const currentGender = gender[i]; const currentAge = age[i]; if (currentGender === "man" && currentAge > 18) { maleOver18++; } else if (currentGender === "woman" && currentAge < 18) { femaleUnder18++; } } console.log(`男性年龄超过18岁人数:${maleOver18}`); // 输出 2 console.log(`女性年龄低于18岁人数:${femaleUnder18}`); // 输出 1
优势:
- 时间复杂度O(n):仅遍历数组一次
- 空间复杂度O(1):无需额外存储符合条件的元素,内存占用极小,适合大数据量场景
二、先存符合条件元素再取长度(适合需复用元素的场景)
如果后续需要使用符合条件的元素数据(比如展示详情),可以先筛选出对应元素,再通过数组长度获取统计数。但仅统计数量时,这种方式效率略低于直接计数。
代码示例(两次筛选):
const gender = ["man","woman","man","man","woman"]; const age = [30,20,13,63,9]; // 筛选符合条件的元素 const validMales = gender.filter((g, index) => g === "man" && age[index] > 18); const validFemales = gender.filter((g, index) => g === "woman" && age[index] < 18); // 通过数组长度获取统计数 const maleOver18 = validMales.length; const femaleUnder18 = validFemales.length;
代码示例(先配对再筛选):
// 先将性别与年龄配对成对象数组 const pairedData = gender.map((g, index) => ({ gender: g, age: age[index] })); // 筛选并统计 const maleOver18 = pairedData.filter(item => item.gender === "man" && item.age > 18).length; const femaleUnder18 = pairedData.filter(item => item.gender === "woman" && item.age < 18).length;
劣势:
- 两次
filter会遍历数组两次,时间复杂度O(2n) - 需要额外存储筛选后的数组,空间复杂度O(k)(k为符合条件的元素数量),数据量大时内存占用更高
三、用reduce实现(兼顾简洁与效率)
如果想兼顾代码简洁性和一次遍历的效率,可以用Array.reduce完成统计,写法更优雅,且性能与直接计数一致。
代码示例:
const gender = ["man","woman","man","man","woman"]; const age = [30,20,13,63,9]; // 一次遍历完成统计,返回统计结果对象 const counts = gender.reduce((acc, currentGender, index) => { const currentAge = age[index]; if (currentGender === "man" && currentAge > 18) { acc.maleOver18++; } else if (currentGender === "woman" && currentAge < 18) { acc.femaleUnder18++; } return acc; }, { maleOver18: 0, femaleUnder18: 0 }); console.log(counts); // 输出 { maleOver18: 2, femaleUnder18: 1 }
优势:
- 一次遍历完成统计,时间复杂度O(n)
- 代码结构清晰,无需额外声明多个变量
最优方案总结
- 若仅需统计数量:优先选择「直接计数」或「reduce实现」,两者效率一致,后者写法更简洁
- 若后续需要复用符合条件的元素数据:选择「先存数组再取长度」的方式
内容的提问来源于stack exchange,提问作者Arska
相关产品推荐
相关产品推荐

