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

如何用JavaScript实现基于两个数组生成指定二维数组?

JavaScript实现指定二维数组转换需求

原始数据与需求

原始数组:

const days = [3, 5, 7, 9];
const values = [[13, 15, 17, 19], [14, 16, 18, 20]];

需求逻辑:

  • 选中day=5,获取其在days数组中的索引
  • 对values中的每个子数组,取该索引位置的元素,重复子数组长度次,最终生成目标二维数组[[15, 15, 15, 15], [16, 16, 16, 16]]

JavaScript实现代码

const days = [3, 5, 7, 9];
const values = [[13, 15, 17, 19], [14, 16, 18, 20]];

// 获取目标day的索引
const dayIndex = days.indexOf(5);
// 生成结果数组
const res = values.map(subArr => Array(subArr.length).fill(subArr[dayIndex]));

console.log(res); // 输出: [[15, 15, 15, 15], [16, 16, 16, 16]]

代码说明

  1. 获取索引:days.indexOf(5)和Python的days.index(5)功能一致,返回元素5在days中的索引(此处为1)
  2. 遍历生成子数组:使用Array.map()遍历values的每个子数组,对应Python中的列表推导式
  3. 生成重复元素数组:Array(subArr.length).fill(subArr[dayIndex])创建一个与原数组长度相同的新数组,并用指定元素填充,和Python中[i[day_index]] * len(i)的逻辑完全等价

替代写法

如果偏好Array.from,也可以这样实现:

const res = values.map(subArr => Array.from({ length: subArr.length }, () => subArr[dayIndex]));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:02:57