Tally of number series in an array

If my array looks like

[0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10]

How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions.

In this example, the output would be 2 because there are 2 sequences of 10's with four 10's in each sequence.

const values = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10];
const MAX = 10;
const threshold = 3;
let count= 0;

let numberInSeq = 0;

values.forEach(x => {
  if (x === MAX) {
    numberInSeq++;
  } else {
    if (numberInSeq >= threshold) {
      count++
    }
    numberInSeq = 0;
  }
})
return count;

This code should work as intended, but I am open to suggestions for optimizing it further.

Thank you!

Answer №1

Your forEach loop contains some minor mistakes that need to be corrected in order to accurately count sequences. It is important to check the threshold only if the current value matches the specified value, such as MAX in your scenario, and then reset the numberInSeq when the threshold is reached. Additionally, I included a flagger variable, sequenceFound, to prevent counting long sequences more than once.

This approach offers the advantage of being a single pass through the data, resulting in a complexity of O(n) in Big O Notation, unlike multiple pass through solutions.

var sequenceFound = false;

values.forEach(x => {
  if (x === MAX) {
    numberInSeq++;
    if (numberInSeq >= threshold && sequenceFound === false) {
      count++;
      sequenceFound = true;
      numberInSeq = 0;
    }
  } else {
    numberInSeq = 0;
    sequenceFound = false;
  }
});

Answer №2

There is a method that involves combining an array into a string with a single character and then using regex to match 10 followed by that character, checking the length of each match, and reducing it to a single value.

let arr = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10]

let op = arr
        .join('-')
        .match(/(10-)+/g)
        .reduce((o,e)=> (o = e.split('-').length-1 >= 3 ? o+1 : o)  , 0)

console.log(op)

As a side note - It may not be the most efficient way in terms of performance compared to using a for loop.

Answer №3

One approach utilizing regular expressions is shown below:

/, 10{3,}/g

The regex pattern captures all the necessary criteria, but the array must first be converted to a string. This method may differ in efficiency compared to other solutions.

Demonstration

let values = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10];
let str = values.join(', ');
let count = 0;
const rgx = /(, 10){3,}/g;
let result = rgx.exec(str);
while (result !== null) {
  count++;
  console.log(result[0]);
  result = rgx.exec(str);
}

console.log(`count: ${count}`);

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

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

Utilizing fab-icons with CDN in Next.js version 13.4

Currently, I am working with the latest version of Next.js (13.4) and I would like to incorporate a single Icon into my project using Font Awesome CDN to avoid increasing the overall app size. However, when I include the following code snippet in my layou ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. I had it working previously, but unsure when it stopped and I can't spot the issue causing all components to return ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

Create a receipt by utilizing jQuery with dynamically generated inputs

Is there a way to insert the descriptions and amounts of invoice items into the receipt, similar to the due date? The input for this section is dynamic with multiple rows that can be added or deleted. I'm considering using a counter that increments e ...

JavaScript: Obtaining a Distinct Identifier for Various Replicated Entries

Imagine we have an object: var db = [ {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" }, {Id: "202", Player: "Sam",price: "4.22", loc: "PA" }, {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" }, {Id: "204", Player: ...

Using a custom function, automatically initiate audio playback when an Android WebView JS loads

I have a unique JS function specifically designed for the audio tag, which also controls the progress bar. It works perfectly when I click on the associated tag <a onclick="playSound(1)">. However, if I try to initiate it on page load, the function s ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

AngularJS framework may encounter an issue where changes in $scope data do not reflect in the view

I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply() should solve this issue. However, I am encountering an error when trying to implement this solution. https://d ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

Divide a Multidimensional Array into Separate Arrays

I am working with an array that contains information about users. Each user has attributes like their ID, name, and number of records for today and in total. Array ( [0] => Array ( [u_id] => 2 [u_name] => Test ...

Using a combination of ajax and php to enhance the voting system

Thank you for taking the time to read this. I am currently working on improving my skills, so I decided to embark on a project to enhance my knowledge. I have created a basic voting system where each content is displayed using PHP and includes an up or do ...

Contrast in functionality between a pair of variables within a controller

Could you please clarify the distinction between two variables a1 and a2: app.controller("someCtrl",function(){ this.a1=somevalue; var a2=somevalue; }); Also, can you explain the lifespan of variable a2? ...

"Embracing Progressive Enhancement through Node/Express routing and the innovative HIJAX Pattern. Exciting

There may be mixed reactions to this question, but I am curious about the compatibility of using progressive enhancement, specifically the HIJAX pattern (AJAX applied with P.E.), alongside Node routing middleware like Express. Is it feasible to incorporate ...

Exploring the Depths of the DOM: Enhancing User Experience with Jquery

I am facing an issue with my AJAX request in my page. After retrieving data from the database and trying to append it to a div, I am attempting to create an accordion interface without success. Below is a snippet of my source code after the AJAX call: ...