javascript - 计算重复数字并替换最后一个索引中的元素
问题描述
如果 number 的计数1
重复大于或等于12
:将所有元素替换2
为 number 的最后一个索引之后1
。原始数组包含 0,1,-1;我尝试在下面使用它可以工作,如果有任何更简单的解决方案,请建议并帮助提供文档链接以供进一步参考。
var arr = [0, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 0, 1, 1, -1, 0, 1, 0];
var total = arr.reduce((t, i) => i == 1 ? t + i : t, 0);
if (total >= 12) {
var startingIndex = arr.lastIndexOf(1) + 1;
var arr = arr.map((e, i) => i >= startingIndex ? 2 : e);
}
console.log(arr);
如果数组是[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0]
那么结果数组应该是[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1, 2]
如果给定数组,[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
那么结果数组应该是[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,2,2,2,2]
如果给定数组,[1,1,1,1,1,-1,1,1,1,1,1,0,1,1,1,0,-1,0]
那么结果数组应该是[1,1,1,1,1,-1,1,1,1,1,1,0,1,1,1,2,2,2]
解决方案
const oneFill = arr =>
arr.filter(x=>x===1).length >= 12 ? arr.fill(2,arr.lastIndexOf(1)+1) : arr
const array = [
[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0],
[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
]
for(const arr of array)
console.log(JSON.stringify(
oneFill(arr)
))
优化版本使用.some
,找到第12个元素后立即爆发
// fills from the 1 found at the 12th instance of 1
const oneFill = arr => {
let count = 0
// if equals 1 increment and check if counter reached 12, fill with 2s
arr.some((x,i)=>x===1 && ++count >= 12 && arr.fill(2,i+1))
return arr
}
const array = [
[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0],
[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
]
for(const arr of array)
console.log(JSON.stringify(
oneFill(arr)
))
// I don't know if you want lastIndex, or just the 12th index
// Below is a version that finds the lastIndex
const oneFill2 = arr => {
let count = 0
arr.some((x,i)=>x===1 && ++count >= 12) && arr.fill(2,arr.lastIndexOf(1)+1)
return arr
}
for(const arr of array)
console.log(JSON.stringify(
oneFill2(arr)
))
推荐阅读
- telegram - 使用 Pyrogram(电报机器人登录)从电报机器人转发消息
- mockito - Mockito 3.7:MockStatic 失败并显示消息:0 Matchers Expected, 1 Recorded InvalidUseOfMatchersException
- php - 我进入浏览器无法使用谷歌日历 api 接收访问令牌
- bash - 带有来自 bash 脚本的命令的新 iTerm 选项卡
- android - 是否可以在颤振应用程序中模拟一系列点击?
- sql - 实施有关用户和系统之间限制的策略
- javascript - 如何在 vue js 项目中导入字体样式
- java - 4Kb 数组?内存表和 SSTable
- python - 再次运行 While If/Else 语句的问题,直到它在 Python 中中断
- javascript - 在写入文件之前完成承诺