如何在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)));
代码解释
- 确定目标长度:通过
Math.max结合map方法,找出所有输入数组中的最长长度,作为统一的补全目标。 - 补全逻辑:遍历每个数组,若长度已达标则直接保留;若不足,取出数组最后一个元素,生成对应数量的重复元素并与原数组合并。
- 日期注意点:代码中用
new Date()替代了原示例中的Date(),这是因为直接调用Date()返回字符串,而new Date()生成日期对象,更符合常规使用场景;若需完全匹配原示例的字符串格式,可改用Date()。
内容的提问来源于stack exchange,提问作者Aditya Gaonkar
相关产品推荐
相关产品推荐

