如何高效统计对象数组中嵌套attachment数组的元素总数?
更高效的统计实现方案
当然有更简洁高效的实现方式!你原来的代码创建了两个中间数组分步处理,其实我们可以利用数组原生方法直接完成统计,既节省内存又让代码更易读。
方法一:使用reduce + flatMap
这种方式通过flatMap把所有attachment数组展开成一维数组,直接取长度得到总数,再用reduce组装结果对象:
const apple = [{ name: 'alpha', details: [{ "attachment": [123, 456] }, { "attachment": [1454, 1992] }] }, { name: 'beta', details: [{ "attachment": ["12", 189] }, { "attachment": ["maggi", 1890, 2000] }, { "attachment": [1990, 2001, 2901] }] }]; const result = apple.reduce((acc, item) => { // 展开所有attachment并计算总元素数 const totalAttachments = item.details.flatMap(detail => detail.attachment).length; acc[item.name] = totalAttachments; return acc; }, {}); console.log(result); // 输出: { alpha: 4, beta: 8 }
方法二:嵌套reduce累加(性能更优)
如果处理的数据量较大,推荐这种方式——它不需要创建任何中间数组,直接通过嵌套的reduce累加每个attachment的长度:
const apple = [{ name: 'alpha', details: [{ "attachment": [123, 456] }, { "attachment": [1454, 1992] }] }, { name: 'beta', details: [{ "attachment": ["12", 189] }, { "attachment": ["maggi", 1890, 2000] }, { "attachment": [1990, 2001, 2901] }] }]; const result = apple.reduce((acc, item) => { acc[item.name] = item.details.reduce((sum, detail) => { return sum + detail.attachment.length; }, 0); return acc; }, {}); console.log(result); // 输出: { alpha: 4, beta: 8 }
为什么这两种方法更好?
- 避免了创建
appleDetails和appleData这两个中间数组,减少了内存占用 - 代码逻辑更紧凑,直接围绕“统计总数”的核心需求展开,可读性更强
- 第二种嵌套
reduce的方式在大数据量下性能更出色,因为它没有数组展开的额外开销
内容的提问来源于stack exchange,提问作者Siva Pradhan
相关产品推荐
相关产品推荐

