如何为数组中的重复非零元素循环推入指定颜色值?
按规则映射数组元素为颜色值
需求说明
给定两个数组,需保留第一个数组中的0,将其中非0的连续重复元素组依次循环使用第二个数组中的颜色值,得到目标数组。
原始数组
const numArr = [0,5,5,5,1,1,0,0,0,3,3,6,6,6]; const colArr = ['red','blue','yellow']
期望结果
const result = [0,'red','red','red','blue','blue',0,0,0,'yellow','yellow','red','red','red'];
现有代码(未完成循环逻辑)
const numArr = [0,5,5,5,1,1,0,0,0,3,3,6,6,6]; const colArr = ['red','blue','yellow'] function solution(numArr , colArr) { const answer = []; for(let i = 0; i < numArr.length; i++) { const arrElem = numArr[i]; if(arrElem == 0) { answer.push(0); } else { answer.push("red") } } return answer; } console.log(solution(numArr , colArr)) // 预期结果: // answer = [0,'red','red','red','blue','blue',0,0,0,'yellow','yellow','red','red','red'];
解决方案代码
const numArr = [0,5,5,5,1,1,0,0,0,3,3,6,6,6]; const colArr = ['red','blue','yellow'] function solution(numArr , colArr) { const answer = []; let colorIndex = 0; // 跟踪下一个要使用的颜色索引 let currentColor = null; // 记录当前组的颜色 for (let i = 0; i < numArr.length; i++) { const current = numArr[i]; if (current === 0) { answer.push(0); currentColor = null; // 遇到0,重置当前组颜色标记 } else { // 判断是否进入新的非0元素组 if (!currentColor || current !== numArr[i-1]) { // 循环获取下一个颜色 currentColor = colArr[colorIndex]; colorIndex = (colorIndex + 1) % colArr.length; } answer.push(currentColor); } } return answer; } console.log(solution(numArr, colArr)); // 输出:[0, 'red', 'red', 'red', 'blue', 'blue', 0, 0, 0, 'yellow', 'yellow', 'red', 'red', 'red']
代码逻辑说明
- 用
colorIndex维护下一个要分配的颜色索引,通过取模运算实现colArr的循环使用 - 用
currentColor记录当前连续非0组的颜色,遇到0时重置该标记 - 遍历数组时:
- 遇到
0直接推入结果数组,同时重置currentColor - 遇到非0元素时,若
currentColor为空(前一个元素是0)或当前元素与前一个元素不同(进入新组),则从colArr中取对应颜色赋值给currentColor,并更新colorIndex - 同一组内的非0元素直接重复推入
currentColor
- 遇到
内容的提问来源于stack exchange,提问作者white-dole
相关产品推荐
相关产品推荐

