Home > Back-end >  Is there more easier way to count same items that goes in row in array?
Is there more easier way to count same items that goes in row in array?

Time:12-01

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.

Is there a way to do it without making a string? Or at least to merge block with while into one?

CodePudding user response:

You can iterate each element in the array.

While doing so, you can keep track of:

  • the total number of repeated groups that have occurred (total)
  • the value of the previous element seen in the array (previousElement)
  • the current number of elements that have repeated (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

  • Related