You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算嵌套对象数组中各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 }
]

关键步骤说明

  1. 扁平化数组:使用data.flat()将嵌套的二维数组转换为一维数组,简化后续遍历逻辑。
  2. 分组统计:通过reduce方法遍历扁平化后的数组,以单词为键构建统计对象:
    • 首次遇到单词时,初始化其min和max为当前count值;
    • 后续遇到同一单词时,用Math.min和Math.max更新对应的最小值和最大值。
  3. 格式转换:使用Object.values()将统计对象的键值对转换为目标格式的数组。

内容的提问来源于stack exchange,提问作者Mattias Törnqvist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:40:30