Discovering the most efficient route among a collection of objects in JavaScript

Presented here is an array of objects:

const data = [
    { start: "X", end: "Y", distance: 5},
    { start: "X", end: "Z", distance: 4},
    { start: "Z", end: "Y", distance: 8},
    { start: "Y", end: "V", distance: 9},
    { start: "V", end: "Z", distance: 17},
]

The task at hand is to determine the shortest path based on 'distance' from point X to Y. To achieve this, a 2D distance matrix has been created.

findUniquePoints() {

        let _points = []
        data.forEach(item => {
            if (!_points.includes(item.start)) {
                _points.push(item.start)
            }
            if (!_points.includes(item.end)) {
                _points.push(item.end)
            }

        })
        return _points
    }

    this.pointsArray = this.findUniquePoints()
    let _matrix = []
    this.pointsArray.forEach((point, index) => {
        _matrix[index] = this.pointsArray.map(() => 0)
   })

   data.forEach(item => {
       _matrix[this.pointsArray.indexOf(item.start)][this.pointsArray.indexOf(item.end)] = item.distance
   })
   console.log(_matrix)
  // The log displays the populated matrix:
  //[[0, 5, 4, 0][0, 0, 0, 9][0, 8, 0, 0][0, 0, 17, 0]]

Answer №1

Implementing a variation of the Dijkstra pathfinding algorithm, construct a map detailing the steps to reach each destination while keeping a record of the path taken:

var obstacles = [
    { start: "A", end: "C", distance: 5 },
    { start: "A", end: "D", distance: 4 },
    { start: "D", end: "C", distance: 8 },
    { start: "C", end: "B", distance: 9 },
    { start: "B", end: "D", distance: 17 },
];
function findOptimalPath(start, end) {
    var openList = obstacles
        .filter(function (item) {
            return item.start == start || item.end == start;
        });
    var resultMap = {};
    resultMap[start] = { distance: 0, route: start };
    obstacles
        .filter(function (item) {
            return item.start == start || item.end == start;
        })
        .forEach(function (value, index) {
            if (resultMap[value.end] === void 0) {
                resultMap[value.end] = { distance: value.distance, route: start + value.end };
            }
            else if (resultMap[value.end].distance > value.distance) {
                resultMap[value.end] = { distance: value.distance, route: start + value.end };
            }
        });
    while (resultMap[end] === void 0) {
        for (var node in resultMap) {
            if (resultMap.hasOwnProperty(node)) {
                var currentNode = resultMap[node];
                obstacles
                    .filter(function (item) {
                        return item.start == node || item.end == node || item.start == node || item.end == node;
                    })
                    .forEach(function (value, index) {
                        var totalDistance = value.distance + currentNode.distance;
                        if (resultMap[value.end] === void 0) {
                            resultMap[value.end] = { distance: totalDistance, route: currentNode.route + value.end };
                        }
                        else if (resultMap[value.end].distance > totalDistance) {
                            resultMap[value.end] = { distance: totalDistance, route: currentNode.route + value.end };
                        }
                        if (resultMap[value.start] === void 0) {
                            resultMap[value.start] = { distance: totalDistance, route: currentNode.route + value.end };
                        }
                        else if (resultMap[value.start].distance > totalDistance) {
                            resultMap[value.start] = { distance: totalDistance, route: currentNode.route + value.end };
                        }
                    });
            }
        }
    }
    return resultMap[end];
}
//TEST
var bestRoute = findOptimalPath("A", "B");
console.log(bestRoute);

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

Ways to transfer a value from a JavaScript file to a PHP file?

Is there a way to transfer data from a JavaScript file to a PHP file? Code: var year = (year != null) ? year : '".$this->arrToday["year"]."'; var month = (month != null) ? month : '".$this->ConvertToDecimal($this>arrTod ...

Obtaining the following class name from elements

I am struggling with extracting classes from a block of HTML code: <div class="container"> <div class="item first">...</div> <div class="item second">...</div> <div class="item third">...</div> <div cla ...

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

What is the method for converting a canvas to a jpg file in Ionic?

I am trying to save a canvas as a jpg image using two different methods. Method A involves converting the canvas data to base64 and then creating a blob to save the image, while Method 2 also converts the data to base64 but uses a custom function to create ...

Exploring Angular2 components featuring setInterval or setTimeout functions

I have a basic ng2 component that interacts with a service to retrieve carousel items and automatically cycle through them using setInterval. Everything functions properly, but I encounter the error "Cannot use setInterval from within an async test zone" w ...

Bring in camera from gltf

Can someone provide guidance on utilizing a camera from gltf within three-js? I am currently implementing the gltf loader as demonstrated in this example. ...

Why is my Angular router displaying the page twice in the browser window?

Angular was initially loading the page on the default port localhost:4200. I wanted it to serve as localhost:4200/specialtyquestions when the app builds, and that is working, but the pages are appearing twice in the browser. Any ideas on what might have be ...

Is there a way to replace null values with empty strings when using json_encode?

I'm struggling to change null values to empty strings in the output of my json_encode: if ($uresult->num_rows >0) { while($urow = $uresult->fetch_assoc()) { $rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldi ...

The rotation duplication feature in THREE.js is malfunctioning

I'm encountering a bug where I'm trying to synchronize the rotations of two objects by copying the Quaternion from one object and applying it to another. However, I'm having trouble getting the rotation to be applied to the second object. I ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Attempting to loop through a list and create a retrieval function for each item

My goal is to loop through the style tags and create a GET function for each one. The issue I'm facing is that the GET function is being written with a direct reference to 'styleTags[i]' instead of converting it to the appropriate tag. var ...

What is the best way to verify the information submitted in a form within a Bootstrap modal window

Each row in my list of items has its own set of "action" buttons. One button allows editing the record, while another displays a list of related records loaded dynamically through an Ajax call. When the modal opens, the corresponding record ID is passed to ...

What is the best method for transferring an audio file from an Express (Node.js) server to a Flask server

Successfully uploaded an audio file (e.g., WAV) at the frontend (React) and sent it to the backend (Express/Node.js). Here is my frontend code (App.js) import React, { useRef, useEffect , useState } from 'react' import VexFlow from 'vexflow ...

Utilizing retrieved data from API calls in subsequent Vue 3 methods

Hello, I'm having an issue with using fetched data in a different method within VUE 3. My goal is to load all the data when the app starts and then be able to use it multiple times throughout the code. Here is my current code snippet: const app = Vue. ...

Voiceover on IOS fails to properly read the content inside a div element

When including visual content in a div element below an image or graphic, it is important to close these visual elements for accessibility purposes. I want only the aria-label content to be read aloud by voiceover software, but unfortunately, the label i ...

casperjs is encountering difficulty locating the id even after setting it

Issue with CasperJS not locating the ID after setting it Casper.then(function () { screenLog(); var id = String("_newid_"); var arrow = this.evaluate(function () { var arrows = document.querySelectorAll('span.select2-selection__a ...

Transferring information from JavaScript to Node.js

I have a simple function that I'm trying to create, let's say my javascript data is const data = 1234; How can I send this data to a node server that I've built using the express framework? const express = require("express"); const app = ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Is the token in localStorage valid? Here's how to find out!

Currently, I am integrating my ReactJS frontend with a PHP backend system. When a user logs in, the JWT Token is stored in the localStorage. I have certain static react pages that should only be accessible when a user is logged in, so I have enclosed the ...

Utilizing Multiple MongoDB Connections in a Node.js Application

I am facing an interesting challenge in my Node.js project where I need to connect multiple MongoDB databases. Let me share with you my current setup and the issue that is causing me some trouble. Node Version: v6.12.1 Express.js Version: 4.16.2 Mongoos ...