如何在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)**逐步构建最终结果:- 初始化累加器为包含两个空数组的对象,用
as GroupedTodos指定类型,避免TypeScript类型推断异常。 - 遍历每个待办项时,根据
isUrgent的布尔值,将当前项推入对应数组。 - 每次迭代后返回更新后的累加器,供下一次遍历使用。
- 初始化累加器为包含两个空数组的对象,用
执行后groupedTodos的结构完全符合需求格式。
内容的提问来源于stack exchange,提问作者Nima Zarei
相关产品推荐
相关产品推荐

