Is there a simpler method for tallying identical items occurring consecutively in an array?

This is my unique code snippet

function countTriplets(arr){
    let sequence = (arr.join(''));
    let pointer = -1;
    let tripletCount = 0;

    const findTriplet = (char, start) => {
        return sequence.indexOf(char, start + 1);
    }

    const updateCount = () => {
        tripletCount++;
        pointer += 3;
    }
    
    while((pointer = findTriplet('hhh', pointer)) !== -1 ){
        updateCount();
    }

    while((pointer = findTriplet('ttt', pointer)) !== -1 ){
        updateCount();
    }

    console.log(tripletCount);
}

countTriplets(["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"]);

In this implementation, I aim to determine the number of times 't' or 'h' occur consecutively three times in a row.

I am exploring if there exists an efficient way to accomplish this without converting the array into a string or merging the two while loops.

Answer №1

You can loop through each item in the array.

While iterating, you should keep track of:

  • the total count of repeated groups encountered (total)
  • the value of the last element seen in the array (previousElement)
  • the current count of elements that have repeated so far (currentCount)

Here is a practical example illustrating the concept mentioned above, along with explanatory comments:

function countRepeats (numOfRepeated, array) {
  let total = 0;
  let currentCount = 0;
  // Initialize previousElement as an empty object to differentiate from other values:
  let previousElement = {};

  for (const element of array) {
    if (element === previousElement) {
      // Increment the count:
      currentCount += 1;

      if (currentCount === numOfRepeated) {
        // Increase the total count:
        total += 1;
        // Reset current count to 1:
        currentCount = 1;
      }
    }
    else {
      // Reset current count to 1:
      currentCount = 1;
    }

    // Update previousElement value:
    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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display output within an array using PHP?

After creating a hashmap array, I utilized a foreach loop to generate output. The current output is dog@ant dogant antdog <?php $rule = [ "c" => "d", "a" => "o", "t" => "g", "h" => "a", "1" => "@", "e" => "n", "n" => "t" ]; $orde ...

What is the best way to implement multiple store filters in VueJS?

Just dipping my toes into the world of VueJS with my very first major project. I've incorporated 2 filters in this project for my elements - one is a search bar and the other involves checkboxes. Taking a look at my code, you'll notice a computed ...

Performing calculations involving both select and checkbox input values, as well as handling negative numbers

Seeking assistance in creating a feature where users can select a billing term from a dropdown and then choose checkboxes to add to the total. While it works fine on JSFIDDLE, I encounter issues on my website - specifically when selecting all checkboxes, r ...

What is the process for adding custom keys to a sequential array or collection of arrays with Laravel or PHP?

I'm currently exploring ways to assign custom keys to a collection in Laravel. One approach I've come across is utilizing methods like transform or mapWithKeys. $result = $collection->map(function ($item) { return [ 'custom_k ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

Using jQuery to implement translation on scroll

Help needed with the translate-animate attribute. I have an image that I want to move upwards when scrolling down on the page. I understand how to use translateY(px) to shift it, but I'm unsure how to perform this translation while scrolling. I aim to ...

Unable to Retrieve Stripe Connect Account Balance

I've been attempting to retrieve the balance for my connected accounts in Stripe, but every time I make an API call, it keeps returning the platform's account balance instead of the connected account balance. This is happening while in test mode. ...

Tips for automatically filling in fields when a button is clicked in a React application

I'm attempting to pre-fill the form fields that are duplicated with data from already filled fields. When I click the "Add Fields" button, new fields are replicated, but I want them to be pre-populated with data from existing fields. How can I access ...

A guide on acquiring interactive documents from Google Drive

I have a question for those familiar with the Google Drive API v3. How can I successfully download a file from Google Drive when all I have is the fileId, without knowing the specific file type (image, pdf, docs)? I've tried searching for examples or ...

Is the referencing of array elements specific to the implementation of the compiler?

Many times I observe the use of the following syntax for referencing elements in a C array: int someArray[10]; (void*) a = &someArray[x]; It appears that this increments the address by sizeof(int) with certain compilers (like mingw) and by sizeof(voi ...

Why would one pass in the value of undefined?

It has come to my attention that jQuery and related plugins like jQuery.UI often pass undefined as a parameter into their anonymous functions within module definitions. For example: (function($, undefined) { ... })(jQuery); On the other hand, I have obse ...

Can you provide an explanation of what the 'attribution' key does in the tomTomMap.addSource() function?

I came across a solution on how to integrate the openweathermap layer into a tom-tom map: tomTomMap.addSource('owm_source', { type: 'raster', tiles: [ 'https://tile.openweathermap.org/map/clouds_new/{1}/{51}/{20}.png? ...

Combining synchronous and asynchronous code in JavaScript with Node.js and MongoDB

Check out this code snippet: var re = new RegExp("<a href=\"(news[^?|\"]+).*?>([^<]+)</a>", "g"); var match; while (match = re.exec(body)){ var href = match[1]; var title = match[2]; console.log(href); db.news.fin ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

Working with PHP Multidimensional Associative Arrays: How to Retrieve a List of Keys?

Here is a look at the data I have: [204] => Array ( [1] => Array ( [leads] => 9 ) [2] => Array ( [leads] => 15 ) ) [200] => Array ...

Configuring local fonts in Puppeteer using npm

Looking to incorporate locally loaded fonts when generating a PDF using the Puppeteer node module. I successfully implemented web fonts, but this does not meet the specified requirements. Environment Details: Node: v10.18.1, Puppeteer: "puppeteer": "^2 ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...