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

如何用TypeScript简洁获取父数组中每个子数组的第一个元素?

TypeScript提取二维数组子数组首元素的简洁实现

直接使用Array.prototype.map方法就能实现和Python列表推导式一样简洁的效果:

const l1 = [[1,2],[3,4],[5,6]];
const l2 = l1.map(item => item[0]);
console.log(l2); // 输出: [1, 3, 5]

说明

map方法会遍历原数组的每个元素,对每个子数组执行item[0]获取首元素,最终将所有结果收集成一个新数组返回,逻辑和你给出的Python列表推导式完全对应,是TypeScript里最简洁的实现方式。

处理边界情况(可选)

如果你的二维数组中存在空的子数组,item[0]会返回undefined,如果需要过滤掉这些无效值,可以搭配filter方法:

const l1 = [[1,2],[],[5,6], [7]];
// 明确过滤undefined
const l2 = l1.map(item => item[0]).filter(val => val !== undefined);
// 更简洁的写法(仅当首元素不会是0、''、false等假值时适用)
const l2 = l1.map(item => item[0]).filter(Boolean);
console.log(l2); // 输出: [1, 5, 7]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:20:33