[英]Is there more easier way to count same items that goes in row in array?
This is my code这是我的代码
function repeat(arr){
let string = (arr.join(''))
let start = -1
let count = 0
while((start = string.indexOf('hhh', start + 1)) != -1 ){
count += 1
start += 3
}
while((start = string.indexOf('ttt', start + 1)) != -1 ){
count += 1
start += 3
}
console.log(count)
}
repeat(["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"])
In this example I tried to count how many times t or h goes 3 times in row.在此示例中,我尝试计算 t 或 h 连续出现 3 次的次数。
Is there a way to do it without making a string?有没有办法在不制作字符串的情况下做到这一点? Or at least to merge block with while into one?
或者至少将块与 while 合并为一个?
You can iterate each element in the array.您可以迭代数组中的每个元素。
While doing so, you can keep track of:这样做时,您可以跟踪:
total
)total
)previousElement
)previousElement
)currentCount
)currentCount
) Below is an example of what I described above, including comments:以下是我上面描述的示例,包括注释:
function countRepeats (numOfRepeated, array) { let total = 0; let currentCount = 0; // Start with an object because no object strictly equals any other value: let previousElement = {}; for (const element of array) { if (element === previousElement) { // Increment the count: currentCount += 1; if (currentCount === numOfRepeated) { // Increment the total: total += 1; // Reset the count to 1: currentCount = 1; } } else { // Reset the count to 1: currentCount = 1; } // Update the previous element: previousElement = element; } return total; } const total = countRepeats( 3, ["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"], // 1 2 3 1 1 2 1 2 3 1 1 1 2 3 1 // 1 2 3 ); console.log(total); // 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.