What is the most effective way to identify two identical values within an array?

Is there a more efficient way to find two adjacent elements with values of 1:2 or 1:3 in an array without counting the third element? The current method works but appears messy. Any suggestions on optimization, possibly by skipping the next iteration during each loop?

const history = ["1:2", "1:11", "1:9", "1:6", "1:9", "1:2", "1:3", "1:10", "1:9", "1:3", "1:3"];

function getStats(history) {

    let trigger = 0;
    let dfault1 = 0;

    $.each(history, function(index, value) {
        if (((history[index] == '1:2') || (history[index] == '1:3')) && ((history[index+1] == '1:2') || (history[index+1] == '1:3'))) {
            if (trigger === 0) {
                dfault1++;
                    trigger = 1;
            } else {
                trigger = 0;
            }
        } else { 
           trigger = 0; 
        }
    });
    console.log(dfault1);
}

dfault1 = 2 because:

When history[5] equals '1:2' and history[6] equals '1:3', dfault++ (1)

then

When history[9] equals '1:3' and history[10] equals '1:3', dfault++ (2)

p.s. Apologies for any language issues. Feel free to ask for clarification if needed.

Answer №1

Check out this method for tidying it up.

function calculateStatistics(data) {
    isMatch = function(value) {
        return value == "1:2" || value == "1:3";
    };

    count = 0;
    previousValue = null;
    $.each(data, function(i, val) {
        if (isMatch(val) && isMatch(previousValue)) {
            count++;
            previousValue = null;
            return true;
        }
        previousValue = val;
    });

    console.log(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

A guide on Extracting Values from Nested Objects

Although I am not well-versed in JavaScript, I have a small project where I need to use JavaScript. I am attempting to retrieve values from an object nested within another object. However, my code is throwing errors. Below is the snippet of my code with d ...

What is the fate of the code that comes after executing history. push in React?

My go-to for routing is typically the Redirect component. It's straightforward since you just need to return the Redirect component when needed. However, I'm a bit lost when it comes to using history objects. In my code base, after pushing a rout ...

Issue: The getStaticPaths function for /products/[productId] is missing the necessary parameter (productId) which should be provided as a string

Currently, I am working on a NextJS web application and trying to display 3 products from JSON data. While following a tutorial, everything seems to work fine, but as soon as I make my own modifications to create something unique, it doesn't quite fun ...

Using jQuery to toggle an open and close button

My icon functions as an open/close button. When opened, it turns red and rotates 45 degrees. The issue arises when trying to close it. Changing the div class causes the icon to disappear while in its active state. Below is the jQuery code I am using: $(". ...

Discover the status of appcache on a webpage even without a manifest file by utilizing an iframe

Looking to cache two important pages of my web application using Application Cache. Successfully implemented with the iframe technique to specifically cache those two pages without caching the manifest-calling page. However, encountering an issue where I ...

Leveraging the power of online LDA for test data prediction

Currently, I am utilizing online Latent Dirichlet Allocation (LDA) to conduct topic modeling tasks. With the base code derived from the initial Online LDA paper by Hoffman, Blei, and Bach published at NIPS in 2010, I have access to the code here: https://g ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

Tips for managing and capturing errors in Express

const database = require('database'); const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const bodyParser = require('body-parser'); const urlencodedParser = body ...

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

How can "this" be synergized with other components?

Incorporating PHP and jQuery into my project, I am faced with a challenge. Here is what I am attempting to achieve: $(this + ' .my_child_class').html('test'); Within a dynamic list of elements, when I click on a button, I use "this" t ...

Tips for Accessing Values in a Dynamic Array in Vue.js

ArrayOrdered :[ { name :"PRODUCT 1", price :"20", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 2", price :"50", amount:"20", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 3", price :"15.5", amount:"10", Total ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

Get the ability to download numerous files simultaneously with pdfMake

Hello there, I am currently working with the pdfMake plugin in my Angular project. You can find the plugin here: https://github.com/bpampuch/pdfmake. I am facing a problem where I need to download multiple files with different document definitions. I have ...

Discover which npm module includes the lodash dependency

I've encountered a peculiar situation while using webpack to create a production bundle for my application. Even though I haven't explicitly installed `lodash` and it's not listed in my package.json file, I noticed that it's being added ...

Patience is necessary as we await the initialization of the lazily loaded

I'm dealing with a scenario where I have a button triggering an onClick handler. In the onClick function, the first action is: if (this.state.lazyLoadedData === undefined) { await this.loadData(); } The issue arises when I click the button rapid ...

The button is not displaying

When trying to click on the "Open device Access" button within the accordion, it does not appear. It seems like there may be an issue with the JavaScript as the transition from "display none" to "display block" is not functioning properly. The "Open device ...

Avoiding conflicts among jquery prototype/plugin methods

Imagine I have a primary JavaScript file on my website that includes the following code: $.fn.extend({ break: function(){ // Add your custom code here }, cut: function(){ // More code here }, // ...and many other methods }); When using t ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

How can I showcase a timestamp data type element that I fetched from Firestore?

Currently, I am looking to showcase the data stored in my Firestore collection. One crucial element in this collection is the "date" field, which is categorized as timestamp. However, upon attempting to display these values, an error message surfaces: E ...