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

如何使用JavaScript将电影数组按年份分组转换为目标对象?

电影数组按年份分组转换实现方案

你可以通过以下两种常用方式完成数组到按年份分组对象的转换,两种方案都仅需一次遍历即可完成,时间复杂度为O(n)。

方案1:使用reduce()方法实现(推荐)

reduce非常适合这类数组聚合为单个对象/值的场景,核心逻辑是在遍历过程中持续累积分组结果:

  • 遍历每部电影时,先判断累积的结果对象中是否存在当前电影年份对应的键
  • 若不存在则先将该键对应的值初始化为空数组
  • 将当前电影名称推入对应年份的数组,最终返回累积的结果对象即可

实现代码:

const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

const x = movies.reduce((groupRes, movie) => {
  const curYear = movie.year;
  // 当年份不存在时初始化空数组
  if (!groupRes[curYear]) {
    groupRes[curYear] = [];
  }
  groupRes[curYear].push(movie.name);
  return groupRes;
}, {}); // 传入空对象作为初始累积值

运行后x的输出和需求结构完全匹配:

{
  1997: ["Good Will Hunting", "Titanic"],
  1999: ["The Matrix", "Tarzan"],
  2014: ["The Imitation Game"],
  2020: ["Escape from Pretoria"]
}

注:你给出的目标结果示例中存在两处笔误:Good will Hunting的正确拼写为Good Will Hunting、Tarazan的正确拼写为Tarzan,上述代码输出的是和原始电影数组一致的正确值。

方案2:使用普通遍历实现

如果对reduce的语法不熟悉,用forEach或者普通for循环也能实现完全相同的效果,逻辑和reduce方案一致:

const x = {};
movies.forEach(movie => {
  const curYear = movie.year;
  if (!x[curYear]) {
    x[curYear] = [];
  }
  x[curYear].push(movie.name);
});

两种实现没有本质的性能差异,reduce的写法在数据聚合场景下语义更贴合函数式编程习惯,你可以根据自己的代码风格选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:21:14