Iterate over a collection of objects to find connections between the starting and ending points, and retrieve the number of occurrences

My challenge involves analyzing an array of objects containing origin and destination data, and the total volume of objects moving between locations. I am specifically looking to compare flow counts between two cities. For example, when the origin is Vancouver and the destination is San Francisco, the count is 5, but when reversed, the count is 12.

    InOut = [
      {
        "origin": "Pittsburgh, Pennsylvania",
        "dest": "New York, New York",
        "count": 5
      },
      ...
      {
        "origin": "San Francisco, California",
        "dest": "Vancouver, Canada",
        "count": 12
      }
    ]

To extract counts using origins and destinations, I created a function:

    function findValueByKey(array, key, value, key2, value2) {
        ...
    }
    var obj = findValueByKey(InOut, 'origin', 'Vancouver, Canada', 'dest', 'San Francisco, California');
    var obj2 = findValueByKey(InOut, 'origin', 'San Francisco, California', 'dest', 'Vancouver, Canada');
    console.log('obj', obj)
    console.log('obj', obj2)

However, I am struggling to iterate through the array to retrieve all counts. My current attempt is:

    allLocations = [...];
    origDestValues = []
    for(i=0; i< allLocations.length;i++){
      InOutA = findValueByKey(setOne, 'origin', allLocations[i], 'dest', allLocations[i])
      InOutB = findValueByKey(setOne, 'origin', allLocations[i], 'dest', allLocations[i])
      ...
    };

While this approach is flawed as it looks for the same origin/destination repeatedly, I believe it's a step in the right direction. I wanted to demonstrate my efforts before seeking help here. Additionally, my actual array consists of many more cities which I have simplified for this query. Your assistance is greatly appreciated.

Answer №1

Execute this code snippet to view the results:

const inOut = [{
    "origin": "Pittsburgh, Pennsylvania",
    "dest": "New York, New York",
    "count": 5
  },
  {
    "origin": "Pittsburgh, Pennsylvania",
    "dest": "Newark, New Jersey",
    "count": 2
  },
  {
    "origin": "Los Angeles, California",
    "dest": "Seattle, Washington",
    "count": 6
  },
  {
    "origin": "Vancouver, Canada",
    "dest": "Brooklyn, New York",
    "count": 3
  },
  {
    "origin": "Detroit, Michigan",
    "dest": "New York, New York",
    "count": 4
  },
  {
    "origin": "Detroit, Michigan",
    "dest": "Washington, DC",
    "count": 11
  },
  {
    "origin": "Vancouver, Canada",
    "dest": "San Francisco, California",
    "count": 5
  },
  {
    "origin": "New York, New York",
    "dest": "Pittsburgh, Pennsylvania",
    "count": 9
  },
  {
    "origin": "New York, New York",
    "dest": "Detroit, Michigan",
    "count": 7
  },
  {
    "origin": "Philadelphia, Pennsylvania",
    "dest": "Baltimore, Maryland",
    "count": 12
  },
  {
    "origin": "Philadelphia, Pennsylvania",
    "dest": "New York, New York",
    "count": 6
  },
  {
    "origin": "Seattle, Washington",
    "dest": "Los Angeles, California",
    "count": 3
  },
  {
    "origin": "San Francisco, California",
    "dest": "Vancouver, Canada",
    "count": 12
  }
]

// Step 1. Discover all potential cities:
const cities = {}

// We use an object to eliminate duplicates
for (const unit of inOut) {
  cities[unit.origin] = {}
  cities[unit.dest] = {}
}

// Step 2. Create a matrix of all city combinations:
for (const city1 in cities) {
  for (const city2 in cities) {
    if (city1 !== city2) {
      cities[city1][city2] = {
        to: 0,
        from: 0
      }
    }
  }
}

// Step 3. Populate the matrix for both destinations and origins:
for (const io of inOut) {
  cities[io.origin][io.dest].to += io.count
  cities[io.dest][io.origin].from += io.count
}

// Step 4. Option to remove empty pairs with zero transactions
for (const city1 in cities) {
  for (const city2 in cities[city1]) {
    if (cities[city1][city2].to === 0 && cities[city1][city2].from === 0) {
      delete cities[city1][city2]
    }
  }
}

console.log("List of all combinations:")
console.log(cities)

console.log("Data for one city (Pittsburgh, Pennsylvania) can be accessed like this:")
console.log(cities["Pittsburgh, Pennsylvania"])

console.log("Flow between Pittsburgh, Pennsylvania and New York, New York:")
console.log(cities["Pittsburgh, Pennsylvania"]["New York, New York"])

console.log("Reverse flow between New York, New York and Pittsburgh, Pennsylvania:")
console.log(cities["New York, New York"]["Pittsburgh, Pennsylvania"])

console.log("For non-existent pairs (no transactions), you will see undefined:")
console.log(cities["Pittsburgh, Pennsylvania"]["Vancouver, Canada"])

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

Using React.js CSSTransition Component properties with TransitionGroup

Exploring ways to animate a group of divs has led me to discover this example which perfectly fits my needs. However, as I am still new to React, I'm having trouble understanding how the props are passed through the <Fade> component, specificall ...

Loading jQuery on document ready with an Ajax request can lead to slow loading times

My current project involves a significant number of ajax requests being made on document.ready. Additionally, I have ajax requests for every database transaction. These requests are all managed in a JS file, with each ajax request corresponding to a PHP pa ...

Error: An unexpected symbol '||=' was found

I'm facing an issue while trying to create a nextjs project with PDFViewer using @react-pdf-viewer. The error I encountered is "SyntaxError: Unexpected token '||=' when collecting pages. This problem seems to be originating from pdf.js in t ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

sorting in React table not functioning properly for computed column

I have a column titled 'EV/Resource ($ per oz)' that appears to not sort correctly in my react table. Instead of sorting in ascending or descending order, it randomizes the table sort. I'm unsure if I am handling this as a "calculated column ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...

Tips for extracting both the div and entire inner content using JavaScript

I need to retrieve the inner content of a div using JavaScript For example: <div id="content" style="height: 20px; overflow: hidden"> content<br>content<br>content<br> </div> This is my HTML code. I only know the div&apos ...

Modify x and y axes in highcharts for stacked columns

Can anyone assist me in finding charts similar to the one shown below? I am interested in utilizing the stacked column charts provided by the highcharts library. However, I need to modify the presentation of the data values as demonstrated in the image. I ...

utilizing window.location.href to direct to a page with javascript capabilities

I am currently developing my own personal website. It is designed to be very light in terms of loading and content. This website relies heavily on the use of jquery, so if a user's browser does not have JavaScript enabled, the site will not function ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

What is the process for making the default text in a text box appear grayed out?

Hey there! I have this cool idea for a text box. Basically, it starts off with default text but when you hover your mouse over it, the text disappears and you can start typing as usual: If you want to see how it looks like, you can check out this link: N ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

Getting information from a database using PHP and AngularJS through the $http.get method

Currently, I am utilizing an AngularJS script to retrieve data from an external PHP file that is encoded in JSON within an HTML page. The method $http.get(page2.php) has been employed to fetch a JSON-encoded array located in another file. However, the issu ...

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

Merging string arrays in Bash for optimal efficiency

My data includes the following: TEXT='1,2 a,b,c XX,YY' I am looking to transform it into the following output: OUT='1,a,XX 1,a,YY 1,b,XX 1,b,YY 1,c,XX 1,c,YY 2,a,XX 2,a,YY 2,b,XX 2,b,YY 2,c,XX 2,c,YY' I realize that this requires recu ...

Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template> <div class="card m-3"> <div class="card-body"> <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

Jest does not allow mocking a module and validating function invocations at the same time

After setting up a new project using create-app-component, which includes build scripts (babel, webpack, jest), I proceeded to write a React component that requires another javascript file containing a function. The contents of my search.js file are as fo ...

Using the conditional rendering technique in a mapped function within a React table cell

I have an array that is being displayed inside a Table, and I need to compare each object's "userName" property with the header in order to determine where to place the value. If there is no match, it should display a "0". Here is a snippet of the ta ...