Detecting the Presence of 5 Consecutive Numbers in an Array using JavaScript

I am struggling to find a way to identify if a sorted Array consists of 5 numbers in consecutive order. The catch here is that the Array can have duplicate and double-digit numbers mixed within it.

I attempted to implement this logic but unfortunately, my approach seems to be falling short.

var array = [1,3,5,7,7,8,9,10,11]
var current = null;
var count = 0;

for (var i = 0; i < array.length; i++) {
    if (array[i] != current) {
        if (count > 4) {
            return true;
        }
        current = array[i];
        count = 1;
    } else {
        count++;
    }
}

if (count > 4) {
    return true;
}

Answer №1

A simple and direct method to solve this problem is:

var should_be_true = [1,3,5,7,7,8,9,10,11];
var should_be_false = [1,3,5,7,9,11,13,15,17];

var testArray = function(array) {
    var conseq = 1;
    for (var idx = 1; idx < array.length ; idx++) {
        if (array[idx] == array[idx-1] + 1)
            conseq++;
        else
            conseq = 1;
        if (conseq == 5)
            return true;
    }
    return false;
}

console.log(testArray(should_be_true)); //true
console.log(testArray(should_be_false)); //false

For an added twist, here's a different functional approach that indicates the starting position of the sequence, or -1 if no sufficiently long sequence is found:

should_be_true.map(function(curr,idx,arr) {
    return (curr == arr[idx-1] +1) ? 1 : 0;
}).join('').search(/1{4}/); 

Answer №2

An effective strategy would involve:

function checkFiveInARow(array) {

  // comparing if each element is greater than or equal to the previous one
  function compare(element, index, array) { return !index || element >= array[index-1]; });

  // checking if at a specific position, all five comparisons leading up to it are true
  function validate (_, index, comparisons) { 
    return index >= 4 && comparisons.slice(index-4, index).every(Boolean);                         
  }

  return array.map(compare).some(validate);
}

The concept involves first generating an array of boolean values using map, indicating whether each element is greater than or equal to the one before it. This creates an array like [true, true, true, false, true].

The some section verifies if for any element, that element and all preceding four elements are true. If so, it returns true.

Alternate Recursive Approach

Alternatively, a recursive solution could offer simpler readability.

function checkFiveInARow(array) {

  return function _five(array, prev, count) {
    if (count >= 5)        return true;
    if (!array.length) return false;

    var next = array.shift();
    return _five(array, next, next === prev ? count : next >= prev ? count+1 : 0);
  }(array, -999999, 5);

}

Answer №3

let numbers = [1,3,5,7,7,8,9,10,11];
let consecutive=false;
let count=0;
for(let i=0;i<numbers.length;i++){
    if(numbers[i]+1==numbers[i+1]){
        count++;
    }
    else{
        count=0;
    }
    if(count==4){
        consecutive=true;
    }
}
if(consecutive){
    //perform your desired action
}

DEMO

A more refined approach would involve encapsulating this logic in a function like so:

function checkConsecutive(numbers){
    let consecutive=false;
    let count=0;
    for(let i=0;i<numbers.length;i++){
        if(numbers[i]+1==numbers[i+1]){
            count++;
        }
        else{
            count=0;
        }
        if(count==4){
            consecutive=true;
        }
    }
    return consecutive;
}

and then utilizing it in the following way:

let numbers = [1,3,5,7,7,8,9,10,11];
if(checkConsecutive(numbers)){
    //perform your desired action
}

DEMO

Answer №4

   function checkConsecutiveNumbers() {
       var numbers = [1, 3, 5, 7, 7, 8, 9, 10, 12];
       var previous = numbers[0];
       var countOfConsecutive = 1;

       for (var index = 1; index < numbers.length; index++) {
           countOfConsecutive = numbers[index] === previous + 1 ? countOfConsecutive + 1 : 1;
           previous = numbers[index];
           if (countOfConsecutive === 5) return true;
       }

       return false;
   }

Click here to view the code on JSFIDDLE.

Answer №5

After conducting some research, I have discovered the most direct method for counting consecutive values. It's important to note that both ascending and descending values are considered consecutive in this approach (if this is not the case for your scenario, you can adjust the Math.abs() function).

function countConsecutiveValues(array) {
    // Sort the array if it's not already sorted
    var sortedArray = array.sort();

    // Initialize the count variable to track consecutive numbers found
    var count = 1; // There will always be at least one consecutive digit

    for (var i = 0; i < sortedArray.length - 1; i++) {
        // Both ascending and descending orders are counted using Math.abs()
        if (Math.abs(sortedArray[i] - sortedArray[i+1]) == 1) {
            ++count;
        }
    }

    return count;
}

// Example input
var exampleArray = [1,2,4,5,3];
// Expected output
5

Answer №6

This code snippet helps identify the highest number of consecutive occurrences in a given array or in general.

var findMaxConsecutiveOnes = function (arr, number) {
   //checking for boundaries
   if(!number || !arr.length) return;

  // maximum number of consecutives
  let max = 0;

  // counting how many consecutives occur before it ends (starting at 1 as even a single occurrence counts)
  let counter = 1;

  // the next two variables can be ignored if using a for loop instead of while
  let length = arr.length;
  let i = 1; // starting from index 1 to compare with index-1
  while (i < length) {

    if (arr[i] == arr[i - 1]) {

      // increment the counter for consecutive occurrences
      counter++;
    } else {

      // reset the count back to 1
      counter = 1;
    }

    // keep track of the maximum value encountered
    max = Math.max(counter, max);

    // moving to the next iteration
    i++;
  }
  return max== number;
};
console.log(findMaxConsecutiveOnes([5, 5, 5, 1, 1, 1, 1, 1]));

Answer №7

cnt will increment only once, specifically when it encounters two 7s in a row.

Ensure that the line for incrementing is placed within the truthy condition, while the line for resetting is located in the else statement.

// Encapsulate code within a function for testing.
function foo() {
  var array = [1, 3, 5, 7, 7, 8, 9, 10, 11]
  var current = null;
  var cnt = 0;

  for (var i = 0; i < array.length; i++) {
    // Check if the next array element is a consecutive increase and not equal to the current one.
    if (array[i] != current && array[i] === array[i-1] + 1) {
      if (cnt > 4) {
        return true;
      }

      current = array[i];
      cnt++;
    } else {
      cnt = 1;
    }
  }

  if (cnt > 4) {
    return true;
  } else {
    return false;
  }
};

// Invoke the function.
alert(foo());

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

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Issue with NullInjectorError: Failure to provide a custom component - Attempting to add to providers without success

I keep encountering errors during my test attempts... Despite looking into similar issues, I am still facing problems even after adding my custom LoginComponent to app.module.ts providers. It is already included in the imports section. app.module.ts @Ng ...

Adjusting background size using jQuery as the window is resized

Exploring ways to dynamically resize the background image of my website based on the current window dimensions using jQuery. At the moment, I have tried the following approach: $(window).resize(function() { $("body").css({"background ...

Trigger a callback in ASP.NET's CallbackPanel using JavaScript every 10 seconds

I am attempting to automatically trigger the callback of a CallbackPanel using JavaScript in my WebFormUserControl every 10 seconds. While I can trigger it with an ASPxButton and ClientSideEvents, my ultimate aim is to have it start automatically every 10 ...

I'm attempting to install the "firebase" package using npm, but I keep encountering a python-related error message during the installation process

I am experiencing difficulties while attempting to install the firebase package in a local expo-managed project. Unfortunately, I keep receiving the following error message... Here is the error message that I am encountering I have already tried using "e ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Filter the ng-repeat in Angular based on the model's value

Within my "Saving" model, there is a field called "Retailer". I want to implement an ng-repeat directive that displays only items with the same "Retailer" value. Essentially, I am attempting to rectify this issue. <div ng-repeat="saving in savings | ...

Resolve CORS error when uploading images with AJAX and Node.js using FormData

I am incorporating vanilla javascript (AJAX) to submit a form and utilizing Formdata(). The submission of the form is intercepted by nodejs and linked to a database. However, there is an issue that arises when I try to connect with nodejs after adding a f ...

instructions for transferring image filenames to a database with the help of multer and express

While utilizing multer and express to upload a photo, everything appears to be functioning correctly. However, I am encountering issues with sending the image name to the mongoose database. The images are successfully uploaded to the upload directory. Alt ...

Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Using placeholders with inputs in an Angular2 table generated by ngFor

I have an array public example = [['hallo', 'fruit', 'rose'], ['apple','book']] Currently, I am working on creating a table of inputs. The values in this table depend on the specific part that I am usin ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...

Java Multidimensional Array Element Replication

I'm currently facing a challenge in Java with this method. The goal of this method is to accept two multidimensional String arrays and return a copied String array. The arrays sent to the copy method will have random lengths. The logic I'm trying ...

Is there a way to trigger the "day click" event when the "Event Click" is clicked on in Jquery full calendar?

When using a jQuery calendar, there are options for day click and event click functionality. I am specifically trying to only handle the "day click" event, even if an "event" is clicked. In order to achieve this, I have commented out the event click functi ...

Is invalid HTML causing issues with Backbone.js templating in Phonegap?

Summary: When my template file contains valid HTML code, it does not display in Phonegap. The structure of my index.html file is as follows: <body onload="onBodyLoad()"> <div data-role="page"> <a href="#login" id="clickme">C ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

Calculate the total of additional user inputs and show the result in a separate element using JavaScript

Query Is there a way for an element to dynamically show the total of different inputs? Situation I have multiple text boxes all with the same class. There are 4 input fields, each containing a number - Input 1 is "1", Input 2 is "2", and so on. The goal ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...