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

如何在TypeScript中用Map/Filter结合索引提取指定人员年龄?

在TypeScript中结合Map/Filter实现按布尔标记提取人员年龄

给定人员数组:

const people = [{name:"max", age:50}, {name:"sue", age: 43}, {name:"tom", age: 34}, {name:"tim", age: 33}];

布尔标记数组(标记需要提取年龄的人员):

const flags = [false, true, true, false];

需要得到结果:[43, 34]

解决方案

核心思路是通过索引关联两个数组,先筛选出标记为true的元素索引,再根据索引提取对应年龄:

const people = [{name:"max", age:50}, {name:"sue", age: 43}, {name:"tom", age: 34}, {name:"tim", age: 33}];
const flags = [false, true, true, false];

const result = people
  // 生成人员数组的索引列表
  .map((_, index) => index)
  // 过滤出标记为true的索引
  .filter(index => flags[index])
  // 根据索引提取对应人员的年龄
  .map(index => people[index].age);

console.log(result); // 输出 [43, 34]

步骤解释

  1. 生成索引列表:people.map((_, index) => index) 遍历人员数组,忽略元素本身,只保留每个元素的索引,得到 [0, 1, 2, 3]。
  2. 筛选目标索引:.filter(index => flags[index]) 检查每个索引对应的标记值,只保留标记为true的索引,得到 [1, 2]。
  3. 提取目标年龄:.map(index => people[index].age) 根据筛选后的索引,从人员数组中提取对应元素的age属性,最终得到目标结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:10:17