Discover a series of sequential numbers that result from being reduced by 1 using JavaScript

Trying to identify consecutive numbers from an array of numbers has been my latest coding challenge. Here's the snippet I've come up with:

let arr = [4, 3, 5, 4, 3];
let new_arr = [];
for (let i = 0; i < arr.length; i++) {
    let internalArr = [arr[i]];
    new_arr.push(internalArr);
    if (arr[i] - arr[i + 1] === 1) {
        new_arr.push([arr[i], arr[i + 1]]);
    }
}
console.log(new_arr);

I'm struggling with getting more than two elements into the new array. For instance, [5, 4, 3] should also be included in the new_arr. However, currently, I'm only able to form arrays with two elements. Any insights on what might be missing?

Answer №1

To achieve the desired outcome, it is recommended to implement a nested loop structure. One way to do this is by iterating through each index starting from i, and within an inner loop, checking if the subsequent number is 1 less than the current one. If this condition is met, a new array can be created and added to the collection - otherwise, the inner loop breaks out and moves on to the next iteration of the outer loop.

let inputArray = [4, 3, 5, 4, 3];
const allSequences = [];
for (let i = 0; i < inputArray.length; i++) {
  let oneSequence = [inputArray[i]];
  allSequences.push(oneSequence);
  for (let j = i + 1; j < inputArray.length; j++) {
    if (inputArray[j] === oneSequence[oneSequence.length - 1] - 1) {
      oneSequence = [...oneSequence, inputArray[j]];
      allSequences.push(oneSequence);
    } else {
      break;
    }
  }
}
console.log(allSequences);

Answer №2

To create groups of consecutive numbers, you can organize them into sub arrays by following the guidelines in the code snippet below:

// List of numbers
const arr = [4,3,5,4,3,7,2];

// Initialize a new array
const new_arr = [];

// Array to hold consecutive numbers
let sub_arr = [];

// Iterate through the numbers
for(let i=0; i<arr.length; i++) {
  // Add current number to sub array
  sub_arr.push(arr[i]);
  
  // Check if next number is not consecutive
  // If so, add sub array to new array and reset sub array
  if(arr[i] - arr[i+1] != 1) {
    new_arr.push(sub_arr);
    sub_arr = [];
  }
}

// Display result
console.log(new_arr);

If you only want consecutive groups with more than one element:

// List of numbers
const arr = [4,3,5,4,3,7,2];

// Initialize a new array
const new_arr = [];

// Array to hold consecutive numbers
let sub_arr = [];

// Iterate through the numbers
for(let i=0; i<arr.length; i++) {
  // Add current number to sub array
  sub_arr.push(arr[i]);
  
  // Check if next number is not consecutive
  // If so, add sub array to new array and reset sub array
  if(arr[i] - arr[i+1] != 1) {
    // Only add sub array to new array 
    // if it contains more than 1 element
    if(sub_arr.length > 1) new_arr.push(sub_arr);
    sub_arr = [];
  }
}

// Display result
console.log(new_arr);

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

Unable to halt operation when xmlhttprequest.responseText is equal to a particular value

Currently, I am incorporating XmlHttp with Java servlets in the following manner: function btnSave_onclick(){ var xmlHttp; var responseText; if (condition){ var para= "someParamsHere"; var url = "urlHere"; if (window.XMLHttpRequest) { ...

Unveiling the Magic Bytes: Extracting the Image File in Multer for Magic Byte Verification in Express.js

Utilizing the fileFilter option within the multer plugin to determine whether an image should be saved on the server or not. Within the fileFilter function, there is a need to verify the magic bytes of these images in order to ensure they are legitimate a ...

Code working in Chrome but not in Firefox: JavaScript hyperlink issue

Within my Rails project, an HTML file displays the following: <a href='#' id="show_advanced">Show advanced options</a> Upon clicking on the link, JavaScript/JQuery code is executed: jQuery("#show_advanced").click(function() { // ...

Leverage more information by clicking on the xAxis element - Highcharts.js

Currently encountering challenges implementing a 'xAxis clickable' column chart. The goal is to display additional Pie charts below the column chart when a user clicks on an element in the xAxis. https://i.sstatic.net/cXUf2.png The structure of ...

Top button on my website fails to function

I followed a tutorial to add a "back-to-top" button, and it works on my JSFiddle but not on my live page. The button shows up in Safari but doesn't scroll up. Any ideas why? // Contact Form $(document).ready(function() { $("#contactfrm").submit(f ...

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

"Collaborative Array Functionality Failing to Oper

In my sqlite database application, I am trying to share an array across the entire application. Here is what I have done: - Created a singleton class with three arrays defined. - Populating data in the arrays using a common class that is shared across diff ...

A program in C to verify the balance of parentheses

I have developed a program to validate the balancing of parentheses. While there are no errors or warnings, the output is not as expected. There might be an issue in my checkBalanced function. #include <stdio.h> #include <stdlib.h> #include & ...

How can I target only the line item that is currently being hovered over on the y-axis in recharts, instead of all line

There are two distinct lines on the graph representing Attendance and Video Watched. When hovering over the Attendance line, the CustomTooltip's payload variable is receiving two entries, one for each line. Is there a way to retrieve only the data re ...

"Struggling with exceeding time limits on LeetCode problem 852 - Can anyone help with optimizing my

class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { int s=0; int e = arr.size() - 1; int mid = s+ (e-s)/2; while(s<=e){ if(arr[mid-1]< arr[mid] && arr[mid]> ...

Incorporating the parent object into a nested JavaScript function

I have come across similar questions, but my situation seems unique to me. I have simplified my code and turned one line into a comment, but the core concept remains unchanged... function myFunction(options) { var button; options.widgets.forEach(f ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

How to prevent mobile menu transition in Vue when changing routes?

I'm looking for a solution to disable the mobile menu transitions when changing page routes in my app. Initially, I noticed that the menu would stay open when switching pages. To address this issue, I added a route watcher to automatically "close" the ...

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

Learn the technique for showcasing numerous markers on Google Maps, each equipped with its own individualized info windows

https://i.sstatic.net/1tTUD.png // map center var center = new google.maps.LatLng(2.855262784366583, 105.4302978515625); function initialize() { var mapOptions = { center: center, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Create a < ...

Sluggish JQuery Animation When Key is Pressed

I have a situation where I am using JQuery to create animation effects on a div element based on arrow key inputs. However, I am encountering an issue where the animation slows down significantly each time I repeat pressing the arrow key for the current d ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Can someone explain why my request is returning a 403 status code?

Currently, I am working on a web application using django and vue js. Everything was going smoothly until I encountered an issue with my first post request: Here are the components involved: The onsubmit function, the function for making the request, the ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

What are the steps to execute a module designed for NodeJS v6 LTS ES2015 in Meteor 1.4.x?

While I understand that Meteor includes NodeJS as a dependency, I'm facing an issue with a module written in ES6 that has a default argument value set within one of the Class methods. The problem arises when using Meteor v1.4.3.2: (STDERR) packages/m ...