Searching for a specific bus stop within an array based on a designated route

There's an issue at hand.

We have a route with several bus stops.

We need to determine the next stop on this route.

The "_stopNum": "1" indicates that the stop is the first one on the route.

Take a look at a stop example:

{
  "route": [
    {
      "_transport": "regionalbus",
      "_num": "146",
      "_direction": "b-a",
      "_directionName": "Nõva - Harju-Risti - Padise - Ämari - Keila - Harku - Tallinn",
      "_stopNum": "1"
    }
  ],
  "_id": "5701054-1",
  "_id0": "134773",
  "_name": "Laimi",
  "_lat": "59.22155",
  "_lon": "23.67992"
}

You can refer to the scheme I created here to better understand the problem.

Additionally, check out a snapshot of a portion of the array here.

I attempted to use the .find function but struggled to search for an object within an array of objects inside another object in an array of objects. Apologies for the confusion.

Answer №1

// start by gathering all stops from your array
let busStops = routeData.map(stop => stop.route).flat()

// create a function to locate the next stop after a given stop
function findNextStop(currentStop) {
  // find the stop with the same route number (_num) and a stop number that is one greater
  return busStops.find(element => element._num === currentStop._num 
         && parseInt(currentStop._stopNum) + 1 == element._stopNum);
}

Simply use the findNextStop() function and input the currentStop. You can adjust the search criteria in the find() according to your requirements, such as filtering by direction as well.

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

Why is the error message "Invalid field name: '$conditionalHandlers' in 'collaborators..$conditionalHandlers'" popping up now?

Currently, in my Node/Express/Mongoose application (latest versions), I am working on a feature that involves "Projects" with a list of "collaborators" identified by the IDS of "Users". To simplify complex aggregations, I have decided to store these IDS as ...

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Changing Powershell into Nested Json

After spending several days attempting to solve a particular issue without success, I am turning to you for help or guidance. I am currently working on a PowerShell script that generates service accounts in Active Directory and then stores the username an ...

The caching of AJAX POST requests is a common occurrence

In my web application, I have implemented a functionality where a POST request is sent to the URL /navigate.php and it works correctly. However, the challenge arises when the application needs to function offline. In such cases, I aim to display a notifica ...

One issue that may arise is when attempting to use ngOnDestroy in Angular components while rearranging user transitions

Encountered an issue recently with Angular - when the user navigates from component A to component B, component A remains active unless ngOnDestroy is triggered. However, if the user visits component B before going to component A and then leaves, ngOnDes ...

Is there a way to have the span update even if the input stays the same? Currently, it only changes when the input is different

Retrieve results of 3 lines (Ps) by entering a word in the text area and clicking search. If the word is found after clicking the button, a span will be displayed with the count of occurrences as well as the highlighted P(s) where it was found. If the wo ...

Utilizing a custom filter for object manipulation within Vuetify's v-autocomplete

When using vuetify v-autocomplete with an object where the object consists of Key-Value pairs, the search functionality is based on the item-text. In my example, I am displaying the object as {1200-Chloride Systems}. Is it possible to make the search funct ...

What is the best way to locate a table of a specific class using jQuery selectors?

Is there a way to specifically target a table with the class "d" using jQuery selectors? I'm having trouble making it work... var dTableTags = $(".d table"); For instance, an example table would look like this... <table id="thetable" class="d"&g ...

Receiving JSON information from a web address using Javascript

I'm currently faced with a challenge in extracting JSON data from a web server. Despite the absence of errors in my code, I encounter difficulties displaying any output. Below is a snippet of the issue: <!DOCTYPE HTML> <html> <head ...

How to utilize jQuery to replace the first occurrence of a specific

Suppose I have an array structured like this: var acronyms = {<br> 'NAS': 'Nunc ac sagittis',<br> 'MTCP': 'Morbi tempor congue porta'<br> }; My goal is to locate the first occurrence ...

Issue with setting multiple checkboxes in AG Grid

I have a situation where I am trying to select multiple checkboxes on different rows in my application. Each time I click on one checkbox, it gets selected just fine. However, when I click on another checkbox in a different row, the previously selected che ...

Looking to incorporate jQuery Form Wizard with mandatory radio button groups?

Currently, I am utilizing the jQuery Form Wizard plugin from The Code Mine website to transform a form into a wizard format. Myform consists of five pages, each containing approximately four radio buttons. It is crucial that at least one radio button on ea ...

What is the reason for the React component being rendered four times?

My React component is fetching data from Firestore and storing it in the items array. However, I am encountering an issue where the menus variable contains three empty arrays that are being rendered on the page. Initially, I used an async function to fetc ...

Codeigniter not functioning properly with Ajax

I am trying to implement this javascript function $('a[name=deleteButton]').on('click', function () { arr=[]; var arr = $("input[name='post[]']:checked").map(function() { return this.value; }). ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...

Tips for updating the background color when clicking in Vue

I've been attempting to change the background color of an element upon clicking it using Vue, but so far I haven't had any success. Here's what I have come up with, including a method that has two functions for the onclick event in Vue. &l ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

Parsing JSON using Newtonsoft library into specified data type from a collection

I have come up with a list of different types as shown below: var executingAssembly = Assembly.GetExecutingAssembly(); var referencedAssemblies = executingAssembly.GetReferencedAssemblies(); var assembly = referencedAssemblies.Single(x => x.Name.Equals ...

Organizing shared components into a dedicated repository

What is the best way to transfer my React components to a separate repository? I attempted moving the files to a new repo and installing them with npm using the git URL, but when I try to import them they are not functioning as expected. ...