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

如何在TypeScript中用reduce按属性分组对象数组

在TypeScript中使用reduce按isUrgent字段分组待办事项

类型定义

先为待办项和分组结果定义TypeScript类型,保证类型安全:

type TodoItem = {
  id: string;
  todo: string;
  isUrgent: boolean;
};

type GroupedTodos = {
  urgentTodo: TodoItem[];
  notUrgentTodo: TodoItem[];
};

原始待办数组

const todos: TodoItem[] = [
  { id: '1', todo: 'Shopping', isUrgent: false },
  { id: '2', todo: 'Dinner', isUrgent: true },
  { id: '3', todo: 'Doctor appointment', isUrgent: true },
  { id: '4', todo: 'Yard sale', isUrgent: false },
];

使用reduce实现分组

const groupedTodos: GroupedTodos = todos.reduce((acc, currentItem) => {
  currentItem.isUrgent 
    ? acc.urgentTodo.push(currentItem) 
    : acc.notUrgentTodo.push(currentItem);
  return acc;
}, { urgentTodo: [], notUrgentTodo: [] } as GroupedTodos);

代码说明

  • reduce通过**累加器(acc)**逐步构建最终结果:
    1. 初始化累加器为包含两个空数组的对象,用as GroupedTodos指定类型,避免TypeScript类型推断异常。
    2. 遍历每个待办项时,根据isUrgent的布尔值,将当前项推入对应数组。
    3. 每次迭代后返回更新后的累加器,供下一次遍历使用。

执行后groupedTodos的结构完全符合需求格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:23:26