Multidimensional array association

Logically it’s pretty straight forward.

  1. Loop through the routes
  2. Per Route, Loop through Stops
  3. Add Stops who’s RouteName matches the Route

This is not the most optimized solution, but it works. Bear in mind that I’m using reduce to initialize each route as an array.

const routesFeatures = [{
    ObjectId: 1,
    Name: "Rota 1"
  },
  {
    ObjectId: 2,
    Name: "Rota 2"
  },
];
const stopFeatures = [{
    ObjectId: 1,
    Name: "Carga 0",
    RouteName: "Rota 2"
  },
  {
    ObjectId: 2,
    Name: "Descarga 0",
    RouteName: "Rota 2"
  },
  {
    ObjectId: 11,
    Name: "Carga 5",
    RouteName: "Rota 4"
  },
];
const result = routesFeatures.reduce((acc, routeFeature) => {
  acc.push(stopFeatures.reduce((_acc, stopFeature) => {
    if (stopFeature.RouteName === routeFeature.Name) {
      _acc.push(stopFeature.RouteName)
    }
    return _acc;
  }, []))
  return acc
}, []);
console.log(result);

Using a standard for-loop

const routesFeatures = [{
    ObjectId: 1,
    Name: "Rota 1"
  },
  {
    ObjectId: 2,
    Name: "Rota 2"
  },
];
const stopsFeatures = [{
    ObjectId: 1,
    Name: "Carga 0",
    RouteName: "Rota 2"
  },
  {
    ObjectId: 2,
    Name: "Descarga 0",
    RouteName: "Rota 2"
  },
  {
    ObjectId: 11,
    Name: "Carga 5",
    RouteName: "Rota 4"
  },
];

function drawRoutesOptimized(routesFeatures, stopsFeatures) {
  const routeStops = [];
  for (let i = 0; i < routesFeatures.length; i++) {
    routeStops.push([]);
    const routeArray = routeStops[i];
    const route = routesFeatures[i];
    for (let j = 0; j < stopsFeatures.length; j++) {
      const stop = stopsFeatures[j];
      if (stop.RouteName === route.Name) {
        routeArray.push(stop.RouteName)
      }
    }
  }
  return routeStops
}
const result = drawRoutesOptimized(routesFeatures, stopsFeatures);
console.log(result);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top