How to find a bus stop in array by a route?

How to find a bus stop in array by a route?

Problem Description:

i’ve got a problem.

We’ve got a route that serves multiple bus stops.

We’ve got one bus stop from the whole route.

Now how to find the stop that goes next on this route?

The "_stopNum": "1" means the stop is the first in route

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"

I’ve made a scheme that can help to understand the problem.

and also a screenshot of a part of array here

I tried to find through the .find function but did not figure out how to search for object in array of objects inside an object in an array of objects. i messed up sorry

Solution – 1

// first collect all stops from your array
let stops = => a.route).flat()

// let's create a function that finds the next stop after a given stop
function getNextStop(currentStop) {
  // find the stop that has the same route number (_num) and the stop number increased by 1
  return stops.find(element => element._num === currentStop._num 
         && parseInt(currentStop._stopNum) + 1 == element._stopNum);

Just use the getNextStop() function and provide the currentStop to it. You can modify the search conditions in the find() by your needs, maybe you need to filter by the direction as well

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.