Extracting JSON coordinates using JavaScript

My objective is to locate the closest coordinate and arrange the cities that are nearest. In the console log, I want the output to appear like this: 8 city, 63.50590523722971; 5 city, 76.32168761236873. The coordinates seem correct, but I am struggling with how to assign the "city" attribute to result[i] and retrieve it.

var locationcity = [
  {"city":"1 City","value":"61,90"},
  {"city":"2 City","value":"34,97"},
  {"city":"3 City","value":"21,63"},
  {"city":"4 City","value":"19,84"},
  {"city":"5 City","value":"0,81"},
  {"city":"6 City","value":"6,76"},
  {"city":"7 City","value":"43,64"},
  {"city":"8 City","value":"18,64"},
  {"city":"9 City","value":"10,61"},
]

function findClosest(locationcity){
    var result = [];
    for(var i=0; i < locationcity.length; i++){
        for(var j = 1; j < locationcity.length-1 ; j++){
            var x, y , r1 , r2;
            var id = locationcity[i].id;
            var coordinate_x = locationcity[i].value.split(",");
            var coordinate_y = locationcity[j].value.split(",");
            x = coordinate_x[0] - coordinate_y[0];
            y = coordinate_x[1] - coordinate_y[1];
            r1 = Math.pow(x, 2);
            r2 = Math.pow(y, 2);
            result[i] = Math.sqrt(r1 + r2);
        }
    }
   var closest = result.sort();
   $(closest).each(function(){
     var _this = $(this);
     console.log(_this);
   });
}
findClosest(locationcity);

Appreciate any help or guidance on this. Thank you!

Answer №1

If you want to enhance the functionality of the sort function, consider passing an additional function as a parameter:

Rather than simply storing the distance value, also save the corresponding city in the following manner:

result[i] = {'distance': Math.sqrt(r1 + r2), 'city': locationcity[i].city };

When sorting, use a custom sort function like this:

var closest = result.sort(function (a, b) {
   return a['distance'] - b['distance'];
});

Answer №2

It appears you may be interested in displaying and sorting city-to-city distances. Here is a quick implementation, though it could benefit from refactoring:

function findClosestCities(locationData) {

var result = new Array();
for(var i=0; i < locationData.length; i++) {

        var j = i + 1;
        while(j < locationData.length ) {

            var x, y , r1 , r2;
            var cityA = locationData[i].city;
            var cityB = locationData[j].city;
            var coordinatesA = locationData[i].value.split(",");
            var coordinatesB = locationData[j].value.split(",");
            x = coordinatesA[0] - coordinatesB[0];
            y = coordinatesA[1] - coordinatesB[1];
            r1 = Math.pow(x, 2);
            r2 = Math.pow(y, 2);

            var distanceTitle  = cityA + " to " + cityB;
            var distanceValue   = Math.sqrt(r1 + r2);

            result.push({
              "name" : distanceTitle,
              "dist" : distanceValue
            });
            j++;
          }
     }

     var closestDistances = result.sort(function (a, b) {
         return a['dist'] - b['dist'];
     });

     for(var key in closestDistances) {
        console.log(closestDistances[key]);
     }
}

findClosestCities(locationData);

This function aims to sort cities based on their distances between them. I hope this proves helpful to your task!

Best regards.

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

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Convert items to an array utilizing lodash

I need assistance converting an object into an array format. Here is the input object: { "index": { "0": 40, "1": 242 }, "TID": { "0": "11", "1": "22" }, "DepartureCity": { "0": "MCI", "1": "CVG" }, "ArrivalCity": { ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

What steps are necessary to configure .eslintrc to identify the use of 'require'?

I recently started using ESLint and successfully integrated it with IntelliJ. Initially, ESLint did not recognize node out of the box. After consulting the documentation, I created a configuration file named .eslintrc at the project's root folder, sp ...

Converting JSON data into a Pandas dataframe

I am encountering an issue with converting JSON formatted data to a Pandas dataframe. The JSON data I have is structured as shown below and is stored in the variable active_assets - Asset({ 'class': 'us_equity', 'easy_to_borr ...

Dealing with the problem of delayed image loading in AngularJS due to a setTimeout conflict

The issue: Upon page load, some images are still processing and not displaying (even though the image URLs are known). The resolution: To address this problem, a customized directive was developed to showcase a loading spinner as a placeholder until the i ...

What is the best way to create varying DOM elements in Angular according to JSON attributes?

In order to enhance user experience, my application includes a feature that presents release notes to users whenever a new version of the app is deployed. These release notes are stored in JSON format in the backend, structured as follows: { "version" ...

Fire an event following the execution of $state.go()

Is there a way to activate an event once the state has been modified in ui.router? Specifically, I am utilizing the ionic framework alongside angularJS which incorporates angular-ui-router. Note: Below is the pseudo code I am hoping to implement. $state. ...

One-time PHP form submission only

On my website, I offer a variety of PDF download options. To access these downloads, I encourage visitors to sign up using a form. After signing up, they receive a direct link to the chosen PDF in their email. My goal is to streamline the process so that ...

Error: Unable to hash type 'list' while dynamically generating 'variables'

Utilizing lists and dictionaries in a series of loops, I am dynamically creating variables. This method allows me to assign various values to the dictionaries based on certain conditions. To simplify the demonstration, I have removed the loops and manually ...

Tips for avoiding performance bottlenecks in Polymer 1

Environmental Issue Polymer 1 Challenge: I am facing an issue where I have an Array containing 35 objects. When I use a dom-repeat template to create a list of elements (all identical), it takes around 10 seconds for all the elements to render. The ent ...

Guide on changing label background color in React

Would you be able to guide me on how to change the background color of the label in react? I am utilizing react + material ui from this source. You can find information on writing CSS in js at this page. Some plugins like jss-nested are available for this ...

Increase the size of the embedded iframe in your Cordova application by using the pinch-to-zoom

I have been struggling with this issue for the past few days and am having trouble finding a solution.. I am trying to figure out how to embed an iframe in a cordova app (running on an iOS device) to display an external webpage while allowing users to pin ...

Utilize the identical ReactJS hook across multiple components

I've created a hook that pulls data from an API and stores the result in my component's state using setAllCommunitiesFromSponsor. Now I want to use this same hook in another component. Instead of copying and pasting, what is the best way to imp ...

Capturing all response requests from the main process in Electron: A step-by-step guide

I am looking to retrieve the responses for all requests made in my electron app from the main process. In this image, it shows that the desired response can be found in the Response tab rather than the Headers tab on Chrome Dev Tools. Instead of using a ...

The JavaScript window variable is not being returned from an AJAX request without a delay

At the beginning of my script, I set a default value for the name of a kmz file that I need for Google Maps. This value is stored in a window variable. window.kmz="Delaware_River_Basin.kmz" After running an ajax request, I receive the correct value for t ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

The results from the JSON data retrieval in the Retrofit are coming back as

When working with serializable classes, it has been noticed that some values are returning null, specifically 'betterFeaturedImage'. What should be the course of action in this scenario? Additionally, no issues have been encountered with gradle. ...

The pattern on one of the cube faces is mirrored

When using an image for the cube texture, I have noticed that the image displays correctly on three out of four faces, but appears reversed on the fourth face. Below is the relevant code snippet: // Accessing the container in the DOM var container2=docume ...

Navigating JSON responses and requests

Although I'm still relatively new to the programming language Go, I have managed to understand most of it quite well. However, I'm struggling with how JSON should be handled within the language. Let's say I have an access token on the front ...