首页 > 解决方案 > 计算重复数字并替换最后一个索引中的元素

问题描述

如果 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]

标签: javascriptarraysecmascript-6

解决方案


使用过滤器查找有多少,使用填充从最后找到的1开始填充索引

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)
))


推荐阅读