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

使用JavaScript从两个现有数组创建带新索引的数组

实现基于年份索引和数据数组的结构化数组

看起来你需要把年份索引数组和对应的多列数据数组整合为结构更清晰的新数组,下面提供两种常见的实现方案,你可以根据实际需求选择:

方案1:生成包含年份和对应数据的对象数组

这个方案会把每个年份和它对应的一组数据打包成一个对象,方便按年份直接访问数据:

const index = [2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018];
const data = [[null,null,null,63.0], [null,null,57.2307692308,null], [null,null,15.0,27.6666666667], [null,null,10.75,12.0], [null,213.0,14.6666666667,48.5], [null,128.0,21.25,23.0], [627.7647058824,113.0,36.7,19.5], [1201.0,132.0,523.7950819672,146.3708333333], [5414.1873111782,74.6666666667,668.5256916996,739.8781725888], [14697.0882352941,130.5,2812.1279069767,1258.0739856802], [11784.918...]];

// 生成按年份分组的对象数组
const yearBasedArray = index.map((year, idx) => ({
  year,
  data: data[idx] || [] // 处理data长度不足的情况,避免报错
}));

console.log(yearBasedArray);

代码说明:

  • 使用Array.map()遍历年份数组,同时获取对应的索引idx
  • 每个迭代项返回一个对象,包含year(当前年份)和data(对应索引的data数组项)
  • 加入data[idx] || []的判断,防止data数组长度小于index数组时出现undefined

方案2:按数据系列整理数组

如果你的data数组中每个子数组的四个元素对应四个不同的数据系列(比如四个不同的指标),可以把每个系列整理成包含年份和有效数值的数组:

const index = [2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018];
const data = [[null,null,null,63.0], [null,null,57.2307692308,null], [null,null,15.0,27.6666666667], [null,null,10.75,12.0], [null,213.0,14.6666666667,48.5], [null,128.0,21.25,23.0], [627.7647058824,113.0,36.7,19.5], [1201.0,132.0,523.7950819672,146.3708333333], [5414.1873111782,74.6666666667,668.5256916996,739.8781725888], [14697.0882352941,130.5,2812.1279069767,1258.0739856802], [11784.918...]];

// 获取数据系列的数量(假设每个data子数组长度一致)
const seriesCount = data[0]?.length || 0;
const seriesBasedArray = [];

for (let seriesIdx = 0; seriesIdx < seriesCount; seriesIdx++) {
  // 整理当前系列的所有有效数据(过滤null值)
  const seriesData = index.reduce((acc, year, idx) => {
    const value = data[idx]?.[seriesIdx];
    if (value !== null && value !== undefined) {
      acc.push({ year, value });
    }
    return acc;
  }, []);
  seriesBasedArray.push(seriesData);
}

console.log(seriesBasedArray);

代码说明:

  • 先获取数据系列的数量(从第一个data子数组的长度获取)
  • 使用循环遍历每个系列索引
  • 对每个系列,用Array.reduce()遍历年份数组,收集该系列下所有非null/undefined的年份-数值对
  • 最终得到一个二维数组,每个子数组对应一个数据系列的有效数据集合

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:44:49