Looking for assistance to find the largest sequence of 3 consecutive numbers within a string in javascript?

In my function, I am tasked with receiving a string of numbers as input. My objective is to identify the largest consecutive three-digit number within the string and then return it.

function findLargestThreeDigitNum(numString){

    let largestNumber = 0;
    let largestThreeNumber = 0; 

    for(let i= 0; i<numString.length; ++i){
        if(numString[i] === largestNumber){
            largestThreeNumber = largestNumber++
        }
    }
    return largestThreeNumber; 
}

Answer №1

Check out this handy script that can help you find the 3 largest consecutive numbers

function findLargestThreeNums(numString) {
  var nums = [];
  
  // Go through the string to identify all sets of 3 consecutive numbers
  for (var i = 0; i < numString.length - 2; i++) { 
    nums.push(numString.slice(i, i + 3));
  }

  nums.sort() // Sort the list from smallest to largest
  return nums[nums.length - 1] // Return the largest number from the list
}

console.log(findLargestThreeNums("693759936") )

Answer №2

Assuming you have an input string like "123 465 789", here is a method to extract the largest three-digit numbers from it. Split the string by spaces, filter out only the 3-digit numbers, sort them, and then take the last three in the sorted list.

getLargestThreeDigits = numString => numString
                                       .split(" ") // split by spaces 
                                       .filter(n => n.length === 3) // keep only 3 digit numbers
                                       .sort()
                                       .slice(-3) // get the last three

console.log( getLargestThreeDigits("56 456 321 78 987 123 741 2 96 41 58 654") )

Answer №3

Breaking down the problem into smaller tasks and solving them with concise functions can be an effective approach. Here's a breakdown of how we tackle the problem:

  • Convert the given string into an array
  • Divide the array into chunks of three digits, or as close to three as possible
  • Filter out any chunks that do not contain exactly three numbers
  • Convert each chunk of 3 'number' strings into a single number
  • Determine the largest number from the set
  • Return the largest number found

If speed is your primary concern, this may not be the most efficient solution for you. However, if you prefer a solution composed of small, reusable pieces, then this method could be suitable.

const splitIntoAllChunks = size => array => Object.values(
  array
    .reduce((prev, _, i) => ({
      ...prev,
      [i]: array.slice(i, i + size),
    }), {})
);
  
const splitIntoThrees = splitIntoAllChunks(3);

const isLength = length => array => array.length === length;

const stringArrayToNumber = array => Number(array.join(''));

const getMax = (champ, challenger) => challenger > champ ? challenger : champ;

const example = "184727158129123"

const result = splitIntoThrees(example.split(''))
  .filter(isLength(3))
  .map(stringArrayToNumber)
  .reduce(getMax, 0);
  
console.dir(result);

If you prefer sticking closer to your original solution, you can make some adjustments like so:

const testData = "1234596789"

function largestThreeDigitNum(numString){

    let numberSize = 3;
    let largestThreeNumber = 0; 

    for (let i = 0; i < numString.length - (numberSize - 1); i++){
 
        const thisNumber = Number(numString.slice(i, i + 3))
        
        if(thisNumber > largestThreeNumber){
            largestThreeNumber = thisNumber;
        }
    }
    return largestThreeNumber; 
}

console.dir(largestThreeDigitNum(testData))

Answer №4

One way to solve this problem is by using a temporary array to check the values for specific conditions.

We can create an array with some numbers and then define a temporary array where we will store certain values based on specific criteria. By iterating through the original array, we can determine which subset of values meets the required conditions and ultimately find the largest sequence that satisfies our constraints.

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

I am looking to transmit information from flask to React and dynamically generate HTML content based on it

index.py @app.route('/visuals', methods=["GET", "POST"]) def visuals(): global visclass return render_template('visframe.html', images=visclass.get_visuals()) visframe.html <div id='gallery'></div> { ...

Steps to fetch real-time messages (data) from a database using AJAX and Django

I'm trying to implement real-time messaging using Ajax and Django for the backend. I have successfully set up the logic to send messages, but I am struggling with receiving messages instantly when another user sends me a message without having to refr ...

Prevents side-to-side scrolling in the section while enabling scrolling up and down on the

I have a div on my website that allows for horizontal scrolling, while the entire page can be scrolled vertically. When the cursor is over a specific section, it disables vertical scrolling and enables horizontal scrolling within that section. I have imp ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

Tips for creating a nested array in Javascript:

Given the following: var person = {name: "", address: "", phonenumber: ""} I am trying to implement a loop to gather user input (until they choose to stop inputting information by entering nothing or clicking cancel). My goal is to utilize the person obj ...

Understanding the process of reading cookies on the Angular2 side that have been set by the C# server

I'm struggling to understand how the angular code can access the cookie that was set on the server side. I found the following code snippet on GitHub. This C# function sets the cookie in the Response object with the last line of code. My question is, ...

Constance in JavaScript

Looking to create constants in Javascript and seeking advice on the best way to do so. While I am aware that true constants don't technically exist, I'm finding it difficult to change values after exporting them. Are constants necessary? Is the ...

Create engaging animations using JavaScript to draw moving circles on an

I'm attempting to achieve a seamless animation of a moving circle from one set of coordinates to another. In this particular scenario, the circle moves from (10, 10) to (50, 50). Below you can find the code for my Bullet class. Whenever the user press ...

AngularJS button click not redirecting properly with $location.path

When I click a button in my HTML file named `my.html`, I want to redirect the user to `about.html`. However, when I try using `$location.path("\about")` inside the controller, nothing happens and only my current page is displayed without loading `abou ...

What is the process for programmatically injecting a search query to activate the places_changed event for the Google Maps API?

Currently, I am working on a search page that includes a location input field. My goal is to automatically populate this input with a query if a user reaches the page from another source with a search query. Additionally, I want to trigger a place change e ...

Show the div just one time

Hey there, I'm trying to create a StackOverflow-like message display at the top of my page. Everything is set up and configured, but I'm facing an issue - the message only shows up the first time. After that, it disappears. I've read that ...

Incorporating an npm reference into a personalized node within Node-RED

As a novice in both the NodeRed and NodeJs/npm realms, I am embarking on the journey of creating a custom node for the first time. Despite my efforts to follow the official documentation on Creating your first node, I seem to have hit a roadblock. Everyth ...

What is the process for adding two separate animations to one div using CSS?

I have created a simple example where I aim to display the output of a JavaScript function on an HTML page. Furthermore, I want to apply two different animations using CSS to this output. When attempting to apply the animations (clockwise and countercloc ...

Encountered an issue while attempting to verify email through ajax with the database

After reviewing responses from multiple users here, I am aiming to verify if an email is already in the database. Below is the code snippet I am using: **HTML CODE** <div class="form-group"> <div class="col-sm-12"> ...

What is the best way to invoke JavaScript from C# code in Ext.NET?

Within my project, I encountered a situation where the displayed time in Chrome is incorrect while it appears correctly in Explorer. To address this issue, I wrote a JavaScript code, but unfortunately, it did not resolve the problem. Below is the JavaScrip ...

Steps for eliminating empty values from the JSON data

How can I eliminate the properties that have null values in the following input data? var data = [ { "Id": "parent", "Function": "Project Management", "Phase": "(Null)" }, { "Id": "1", "Function": "R&D Team", "Phase": "parent" }, ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

Error: While testing an AngularJS controller with Karma, there was an issue accessing the property 'then' of an undefined variable

I'm currently working on writing unit tests for a controller that receives a promise from a service. However, when using Jasmine, I encounter the following error: TypeError: Cannot read property 'then' of undefined Within the controller, I ...

What is the best way to load the nested array attributes in an HTML table dynamically with AngularJS?

I attempted the following code, but I am only able to access values for cardno and cardtype. Why can't I access the others? Any suggestions? <tr ng-repeat="data in myData17.layouts"> <td ng-show="$index==1">{{data.name}}</td> &l ...

Simulate a click event on an element generated with JavaScript to initiate the download of a CSV file

I am attempting to generate an HTML element and trigger a click event in order to download a CSV file upon receiving an ajax response (the data array provided is for testing purposes only). $(document).on('click','.csv',function(){ ...