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

如何在JavaScript中使多个二维数组长度保持一致?

问题与解决方法

需求说明

给定几组JavaScript二维数组,需将长度较短的数组补全——重复添加其最后一个元素,使所有数组长度保持一致。

原始数组

[[Date(), 1],[Date(), 3], [Date(), 5]]

[[Date(), 5],[Date(), 2]]

[[Date(), 7],[Date(), 3], [Date(), 1], [[Date(), 4],[Date(), 7], [Date(), 3]]]

期望输出

[[Date(), 1],[Date(), 3], [Date(), 5], [Date(), 5], [Date(), 5], [Date(), 5]]

[[Date(), 5],[Date(), 2], [Date(), 2], [Date(), 2], [Date(), 2], [Date(), 2]]

[[Date(), 7],[Date(), 3], [Date(), 1], [[Date(), 4],[Date(), 7], [Date(), 3]]]

实现代码

// 整理原始数组为集合
const inputArrays = [
  [[new Date(), 1], [new Date(), 3], [new Date(), 5]],
  [[new Date(), 5], [new Date(), 2]],
  [[new Date(), 7], [new Date(), 3], [new Date(), 1], [[new Date(), 4], [new Date(), 7], [new Date(), 3]]]
];

// 获取所有数组中的最大长度
const targetLength = Math.max(...inputArrays.map(arr => arr.length));

// 处理每个数组,补全长度
const resultArrays = inputArrays.map(arr => {
  if (arr.length >= targetLength) return arr;
  const lastElement = arr[arr.length - 1];
  const fillCount = targetLength - arr.length;
  return [...arr, ...Array(fillCount).fill(lastElement)];
});

// 打印结果
resultArrays.forEach(arr => console.log(JSON.stringify(arr, null, 2)));

代码解释

  1. 确定目标长度:通过Math.max结合map方法,找出所有输入数组中的最长长度,作为统一的补全目标。
  2. 补全逻辑:遍历每个数组,若长度已达标则直接保留;若不足,取出数组最后一个元素,生成对应数量的重复元素并与原数组合并。
  3. 日期注意点:代码中用new Date()替代了原示例中的Date(),这是因为直接调用Date()返回字符串,而new Date()生成日期对象,更符合常规使用场景;若需完全匹配原示例的字符串格式,可改用Date()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:21