如何计算嵌套对象数组中各word对应的count最小值与最大值?
计算嵌套对象数组中每个单词的count最小值与最大值
输入数据结构
[ [ { word: "china", count: 0 }, { word: "kids", count: 1 }, { word: "music", count: 0 }, ], [ { word: "china", count: 3 }, { word: "kids", count: 0 }, { word: "music", count: 2 }, ], [ { word: "china", count: 10 }, { word: "kids", count: 3 }, { word: "music", count: 2 }, ] ];
需求
计算每个word对应的count字段的最小值和最大值,单个结果格式示例:
{ word: "china", min: 0, max: 10 }
实现方案
可以通过扁平化嵌套数组结合分组统计的方式实现,以下是JavaScript的具体代码:
const data = [ [ { word: "china", count: 0 }, { word: "kids", count: 1 }, { word: "music", count: 0 }, ], [ { word: "china", count: 3 }, { word: "kids", count: 0 }, { word: "music", count: 2 }, ], [ { word: "china", count: 10 }, { word: "kids", count: 3 }, { word: "music", count: 2 }, ] ]; // 扁平化二维数组为一维数组 const flattenedData = data.flat(); // 分组统计每个单词的min和max const stats = Object.values(flattenedData.reduce((acc, item) => { const { word, count } = item; if (!acc[word]) { // 首次遇到该单词,初始化min和max为当前count acc[word] = { word, min: count, max: count }; } else { // 更新最小值和最大值 acc[word].min = Math.min(acc[word].min, count); acc[word].max = Math.max(acc[word].max, count); } return acc; }, {})); console.log(stats);
输出结果
运行代码后会得到包含所有单词统计信息的数组:
[ { word: "china", min: 0, max: 10 }, { word: "kids", min: 0, max: 3 }, { word: "music", min: 0, max: 2 } ]
关键步骤说明
- 扁平化数组:使用
data.flat()将嵌套的二维数组转换为一维数组,简化后续遍历逻辑。 - 分组统计:通过
reduce方法遍历扁平化后的数组,以单词为键构建统计对象:- 首次遇到单词时,初始化其
min和max为当前count值; - 后续遇到同一单词时,用
Math.min和Math.max更新对应的最小值和最大值。
- 首次遇到单词时,初始化其
- 格式转换:使用
Object.values()将统计对象的键值对转换为目标格式的数组。
内容的提问来源于stack exchange,提问作者Mattias Törnqvist
相关产品推荐
相关产品推荐

