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

Kotlin中如何过滤嵌套列表,获取每个剧集系列的最高集数

筛选每个剧集系列中最高集数的元素

给定嵌套结构的剧集列表,要按剧集系列(collection_id)分组,保留每个系列里集数(episode_number)最大的元素,单独用filter无法实现,得先分组再筛选,具体实现如下:

原始数据

const episodes = [
  {
    "media": {
      "episode_number": "7"
    },
    "collection": {
      "collection_id": "26464"
    }
  },
  {
    "media": {
      "episode_number": "6"
    },
    "collection": {
      "collection_id": "26464"
    }
  },
  {
    "media": {
      "episode_number": "9"
    },
    "collection": {
      "collection_id": "123456"
    }
  }
];

实现代码

// 1. 按collection_id分组
const grouped = episodes.reduce((acc, curr) => {
  const id = curr.collection.collection_id;
  if (!acc[id]) {
    acc[id] = [];
  }
  acc[id].push(curr);
  return acc;
}, {});

// 2. 筛选每个分组中集数最大的元素
const result = Object.values(grouped).map(group => {
  return group.reduce((maxEp, currEp) => {
    // 把字符串转成数字再比较,避免字符串排序问题(比如"10"比"2"小)
    return Number(currEp.media.episode_number) > Number(maxEp.media.episode_number) ? currEp : maxEp;
  });
});

console.log(result);

输出结果

[
  {
    "media": {
      "episode_number": "7"
    },
    "collection": {
      "collection_id": "26464"
    }
  },
  {
    "media": {
      "episode_number": "9"
    },
    "collection": {
      "collection_id": "123456"
    }
  }
]

说明

  • 单独用filter无法完成需求:因为filter只能判断单个元素是否符合条件,无法对比同系列的其他元素,必须先通过reduce把同系列的剧集归为一组。
  • 注意episode_number是字符串类型,比较时要转成数字,否则会出现字符串排序的错误(比如"10"作为字符串会比"2"小)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:03:32