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

如何基于单个元素合并多维数组值并统计各州年度分布?

合并同州同年份的数组条目并统计数量

需求说明

有如下多维数组,每个子数组格式为[州名, 原始计数, 年份],需要合并州名和年份都相同的条目,统计这类条目的出现次数(比如佛罗里达州2021年有2条记录,合并后计数为2)。

原始数组

[
  ["Arizona", 1, 2021],
  ["California", 1, 2021],
  ["Florida", 3, 2021],
  ["Florida", 3, 2022],
  ["Florida", 3, 2021],
  ["Mississippi", 1, 2022],
  ["Ohio", 3, 2021],
  ["Ohio", 3, 2022],
  ["Ohio", 3, 2023],
]

期望输出

[
  ["Florida", 2, 2021],
  ["Florida", 1, 2022],
  ["Ohio", 1, 2021],
  ["Ohio", 1, 2022],
  ["Ohio", 1, 2023],
]

用户尝试的代码(存在问题)

let filtered = postsSummary.filter((el) => el[3].includes(2021));

console.log(filtered);

问题点:

  1. 子数组只有3个元素,年份对应的索引是2,el[3]不存在;
  2. filter仅能筛选元素,无法完成合并统计的聚合操作。

解决方案

可以用reduce先完成分组统计,再转换为目标格式的数组:

const postsSummary = [
  ["Arizona", 1, 2021],
  ["California", 1, 2021],
  ["Florida", 3, 2021],
  ["Florida", 3, 2022],
  ["Florida", 3, 2021],
  ["Mississippi", 1, 2022],
  ["Ohio", 3, 2021],
  ["Ohio", 3, 2022],
  ["Ohio", 3, 2023],
];

// 分组统计:用"州名-年份"作为唯一标识,累计出现次数
const stats = postsSummary.reduce((acc, [state, _, year]) => {
  const key = `${state}-${year}`;
  acc[key] = acc[key] ? acc[key] + 1 : 1;
  return acc;
}, {});

// 转换为期望的数组格式
const result = Object.entries(stats).map(([key, count]) => {
  const [state, year] = key.split("-");
  return [state, count, Number(year)];
});

// 如果只需要保留佛罗里达和俄亥俄的结果,再加一层过滤
const filteredResult = result.filter(([state]) => ["Florida", "Ohio"].includes(state));

console.log(filteredResult);

代码说明

  1. reduce遍历数组,以州名-年份为键,在对象中记录每个组合的出现次数;
  2. Object.entries把统计对象转为键值对数组,再拆分键得到州名和年份,组合成目标子数组;
  3. 最后可选过滤出指定州的结果,匹配你的期望输出。

内容的提问来源于stack exchange,提问作者mmcglynn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:54:16