JS/TS实现按目标数组长度循环重复填充数组元素
问题描述
我有两个长度动态变化的字符串类型数组,示例代码如下:
const categories = ['apple', 'pear', 'melon', 'lemon'] const colors = ['red', 'blue', 'green']
需要实现的效果:保证colors.length >= categories.length,colors数组中缺失的元素按照原有顺序循环重复取已有元素填充,效果示例如下:
- categories长度为4时:
const categories = ['apple', 'pear', 'melon', 'lemon'] const colors = ['red', 'blue', 'green', 'red'] // colors[3] = colors[0]
- categories长度为6时:
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange'] const colors = ['red', 'blue', 'green', 'red', 'blue', 'green']
- categories长度为7时:
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange', 'cherry'] const colors = ['red', 'blue', 'green', 'red', 'blue', 'green', 'red']
目前初步编写了如下函数框架,但不知道如何正确实现colors数组元素的循环重复逻辑:
function adjustLenghts(categories: string[], colors: string[]) { const overflowingCategoriesItems = domain.slice(colors.length, categories.length) const repeatedRange = ?? const newColors = ?? return newColors }
实现方案
核心思路是用索引取模实现循环取值:对任意位置的索引,用它对原colors数组的长度取余,得到的结果永远落在原colors数组的合法索引范围内,天然实现循环复用元素的效果,不需要手动计算重复轮次、切片拼接。
简洁版实现(推荐)
直接按categories的长度生成目标数组,逻辑最简洁,没有冗余判断:
function adjustLengths(categories: string[], colors: string[]) { // 注意:如果业务场景允许colors为空,需要在这里加边界判断,避免取模报错 const originColorLength = colors.length; return Array.from({ length: categories.length }, (_, idx) => colors[idx % originColorLength]); }
逻辑验证:
- 原colors长度为3时,索引3 → 3%3=0 → 取
colors[0]即red - 索引4 → 4%3=1 → 取
colors[1]即blue - 索引5 → 5%3=2 → 取
colors[2]即green - 索引6 → 6%3=0 → 回到red,完全匹配需求示例。
贴合原有框架的实现
如果要沿着你最初的「先取溢出部分、再补全元素」的思路写,可以参考下面的代码,同时修正了原框架里的拼写错误(lenght→length)和无效变量(domain不存在,替换为categories):
function adjustLengths(categories: string[], colors: string[]) { // colors长度已经满足要求时,直接返回原数组的副本即可 if (colors.length >= categories.length) { return [...colors]; } const needFillCount = categories.length - colors.length; const newColors = [...colors]; for (let i = 0; i < needFillCount; i++) { newColors.push(colors[i % colors.length]); } return newColors; }
两种实现的运行效果完全一致,都能覆盖所有动态长度的场景。
内容的提问来源于stack exchange,提问作者marielle
相关产品推荐
相关产品推荐

