How can I retrieve the number of links pointing to a specific property within a JavaScript object

I am faced with the following dataset:

const main = 'test1';
const data = [
  {
    from: 'test1',
    to: 'test2'
  },
  {
    from: 'test2',
    to: 'test3'
  },
  {
    from: 'test3',
    to: 'test4'
  },
  {
    from: 'test4',
    to: 'test2'
  },
  {
    from: 'test1',
    to: 'test4'
  }
];

My goal is to determine the number of connections to the main node (in this case test1). For instance, if we consider node test3, it requires 2 links to reach test1:

        test3 → test2 → test1

The same applies to node test2, where only 1 link is needed to arrive at test1.

What would be the most efficient approach to calculate this? Ultimately, I aim to find the longest chain of connections leading to test1. In this particular example, it amounts to 3:

        test3 → test2 → test4 → test1

Answer №1

To cover all possible paths, one must explore each one individually. However, if a loop is encountered and the desired destination can still be reached, then the longest distance becomes infinite because one can circle through the loop indefinitely.

An efficient way to explore all paths is by using a recursive function like this:

function find(data, sourceName, targetName) {
    // Create a data structure mapping nodes by their names
    const map = new Map(data.map(({from}) => [from, []]));
    data.forEach(({from,to}) => map.get(from).push(map.get(to)));
    
    // If traversing both directions is allowed (undirected links), uncomment the following line:
    // data.forEach(({from,to}) => map.get(to).push(map.get(from)));

    const target = map.get(targetName);
    
    // Recursive function definition
    function recur(node) {
        if (node === target) return 0; // Found target
        if (node.visited) { // Detect and handle cycles during backtracking 
            node.onCycle = true;
            return -Infinity;
        }

        node.visited = true;
        let dist = 1 + Math.max(...node.map(recur)); // Maximize path length
        node.visited = false;

        // Exclude if longest path should not include cycles
        if (node.onCycle && dist > 0) return Infinity; // Solution path may contain cycles

        return dist;
    }
    
    const dist = recur(map.get(sourceName)); // Begin search!
    
    return dist < 0 ? null : dist; // Return null when target cannot be reached
}

const data = [{from: 'test1', to: 'test2'},{from: 'test2', to: 'test3'},{from: 'test3',to: 'test4'},{from: 'test4',to: 'test2'},{from: 'test1',to:'test4'}];
const longestDist = find(data, 'test1', 'test3');
console.log(longestDist);

Note that this code does not continue searching beyond the target node while trying to reach it again from there (via a cycle). It assumes a path can only have the target as its last node once, not multiple times.

If you prefer to exclude paths with cycles, delete the line returning Infinity for distance.

This implementation assumes directed links. If links are bi-directional (undirected), where specifying one direction implies the opposite direction without explicitly defining it, uncomment the second forEach line in the provided code snippet.

Answer №2

In the realm of graph theory, your query can be reframed as follows: Each "test1", "test2",... represents a vertex, while the data array stores edges connecting these vertices (in pairs of "from-to"). Thus, we have a graph - and determining the longest path within this graph poses a challenge known as an NP-hard problem (link to wiki). To pinpoint the longest path, one must explore all potential routes meticulously.

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

Unable to delete data in Laravel 8

I am new to Laravel and facing an issue when trying to delete a row with a modal. The problem is that only the first row is getting removed and I can't figure out the reason. Here is my modal setup: <p class="card-text"><small clas ...

What steps can be taken to ensure that any new elements generated by JavaScript do not disappear upon refreshing the page

I am currently working on a project where I am creating a list by collecting user information and storing it in a MySQL database. When the user clicks the 'add' button, a new element is added to the bottom of the existing list which is coded in H ...

A step-by-step guide on disabling Google Analytics in a Next.js document.js file

Upon a user's initial visit to the website, they are presented with the option to either accept or decline tracking cookies. If the user declines, a cookie is set with the value of false. I am in need of a way to conditionally run the gtag script base ...

Struggling to showcase array data in a visually appealing table format?

Hello, I am currently facing the following issue Here is a snapshot of my current website; https://i.sstatic.net/pNXNx.png I am trying to display content in a table from an array stored in a JSON file. Initially, I used a foreach loop which worked perfe ...

What is the process for utilizing jQuery's advanced ticker feature to extract content from a text file?

I am currently implementing this code on my website: <script> var file = "http://newsxpressmedia.com/files/theme/test.txt"; function getData(){ $.get(file,function(txt){ var lines = txt.responseText.split("\n"); for (var i = ...

Discovering escape characters while iterating through a string in javascript

I have a situation where I must rearrange a string into an array for a unique user display. Whenever encountering an escape character (such as \n for a new line), it needs to be added as a separate item in the array. For example, if the string is: sa ...

Tips on deleting information from an object by utilizing Chrome storage mechanisms

In the chrome storage, I have an object structured as follows: { "planA": { 123: {key: 'some key'} 124: {key: 'some other key'} }, "planB": { 223: {key: 'some key'} 234: { ...

Attempting to send JSX as a prop value

IMPORTANT UPDATE: Good news - the code is actually functioning correctly! The issue was caused by a header element obstructing the content, leading to confusion. Apologies for any misunderstandings! I am attempting to pass a simple <p> JSX tag as a ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

Employing live labels on a Morris Bar Chart

I'm using the Morris Bar Chart to showcase the sales of different products. To enhance user experience, I want to display dynamic labels when hovering over the bars. The data is being fetched through PHP. array('product' => $row['pr ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

Guide to placing an image in a designated position

I am looking to achieve the following scenario: Whenever a user uploads an image, it should appear in one of the smaller boxes on the right. Subsequent image uploads by clicking on the big box should populate the other small boxes on the right. Please refe ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

Determine the available time slots for reserving a resource

I am developing an application that displays the weekly availability (Monday-Sunday) of a bookable resource. Next to this calendar view, users can select: A) Length of desired booking slot (15 min/30 min/60 min) B) Time zone The time slots are based ...

The search results fail to show the required information

I am trying to retrieve data from an API based on a search query. When the user enters the name of the film they are looking for and hits enter to submit the form, the matching films should be displayed on the screen. However, my console is showing errors ...

Sending JavaScript array to PHP server-side script

In my current Web application project, I am faced with the task of working with two different lists. To achieve this, I need to convert the list into an array and then pass this array from JavaScript to PHP for further analysis. Below is a simplified exam ...

import a function from jQuery that has been defined in an external JavaScript file

Whenever I attempt to execute this action, I encounter an error stating that the function is undefined $(function () { function Example(){ Example1(); } Example1(); }); external.js $(function () { function Example1(){ alert("Hello"); } }); ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...