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

JavaScript如何提取二维数组各子数组首元素生成扁平化一维数组

实现代码

你可以直接使用数组map方法遍历原二维数组,提取每个子数组的第一个元素即可,示例代码如下:

var array = [['test1', 0], ['test2', 3], ['test4', 45]];
// 箭头函数写法
const res = array.map(item => item[0]);
console.log(res); // 输出 ['test1', 'test2', 'test4']

如果需要兼容低版本ES环境,可使用ES5写法:

var res = array.map(function (item) {
  return item[0];
});

如果需要处理子数组为空的异常场景,避免返回undefined,可以改用reduce方法做判断:

const res = array.reduce((acc, cur) => {
  // 仅当子数组存在且非空时才取第一个元素
  if (cur && cur.length) acc.push(cur[0]);
  return acc;
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:12:03