What is the best way to arrange an array by comparing to the previous element?

I am currently working on a JavaScript challenge: I have an array of random map coordinates (latitude, longitude) stored like this:

var coordinates = [
[64,22],[55,33],[28,35],[...,...]
]

Additionally, I have a function that calculates the distance between two points:

For example:

var getDistance = function(point1, point2)
    {
    return L.dist(point1, point2); //using Leaflet method
    }

Here is where I'm struggling:

How can I rearrange my array to sort the distances by closest proximity from the first coordinate, then from the second, third, and so on? Does anyone have a solution for this? I feel stuck :(

edit 1 :

I attempted to tackle the issue with a nested loop, but the results are not as expected.

var closestIndex = 1;
var closestDistance = 99999999;

for (var i = 0; i < coords.length; i++) {
    for (var j = i + 1; j < coords.length; j++) {
        if ((Map().distance(coords[i], coords[j]) < closestDistance) && 
            (Map().distance(coords[i], coords[j]) != 0)) {

            closestDistance = (Map().distance(coords[i], coords[j]));
            closestIndex = j;
        }
    }
    
    console.log("CD", closestDistance + "(" + closestIndex + ")");
    finalArray.push(coords[closestIndex]);
    coords.splice(closestIndex, 0);
    cloestDistance = 9999999;
}

Answer №1

What is the best approach to organize my array based on the distance from the first coordinate to the closest, then to the second closest, and so on?

The task you are describing does not fit the definition of a typical "sort," as it involves finding the closest distance to each previous point rather than applying a standard ordering. A more appropriate term would be organizing them by their proximity to a single point.

To achieve your desired outcome, it is recommended to precisely follow your instructions. Begin by adding the first coordinate to the result array, then locate the closest point to that in the remaining coordinates and include it. Continue this process until all coordinates have been accounted for.

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

Managing the verification of data existence in the ExpressJS service layer or controller

Working on a medium-sized website, I realized the importance of writing maintainable code with a better project structure. After stumbling upon this insightful article and some others discussing the benefits of 3-layer architecture, I found the concept qu ...

What steps need to be taken to implement a structured autocomplete feature?

Let me break down the workflow for you: The user inputs something in a text field. Upon keypress, the frontend communicates with our backend script to retrieve and select a specific value. Once the value is selected, on leaving the input field, we query ...

What is the method for extracting JavaScript code as data from a script tag?

I have a file external (let's say bar.js) function qux() {} Then in my webpage, I include it using the script tag: <script type="text/javascript" src="bar.js"></script> I am looking for a way to retrieve the JavaScript code from within ...

Can you explain the significance of Angular 2 hashtags within a template?

Currently exploring Angular 2 and stumbled upon the following code: <input #searchBox (keyup)="search(searchBox.value)" Surprisingly, it works! Despite its functionality, the significance of #searchBox eludes me. Extensive research in the documentati ...

Shadowing jQuery variables involves declaring a new variable with the

There seems to be an unusual pattern used in jQuery: var jQuery = (function() { // This local copy of jQuery is defined within a closure var jQuery = function( selector, context ) { ... return jQuery; })(); Why was this approach chosen? Instead of exp ...

Troubleshooting issue: AngularJS NVD3 line chart directive does not refresh after data update (not updating in real time)

I am currently facing an issue with the nvd3-line-chart directive in my AngularJS application. The chart does not redraw when I change the underlying model... As a newcomer to AngularJS, there may be something obvious that experienced programmers will not ...

Is there a way to ensure that when a user updates the src attribute of a video element in a REACT Gutenberg block, the change is immediately visible to them?

I am currently in the process of developing a custom Gutenberg block for WordPress by utilizing @wordpress/create-block. As part of this project, I am incorporating the MediaUpload React component, which can be found at this link. Within the block, there ...

What is the best way to retrieve a JSON element obtained from a Parse.com query?

I'm encountering difficulties when attempting to access a specific JSON element that I receive in response from a query made into a Parse.com Class. Despite reading through various questions and answers on similar topics, I have yet to find a solutio ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Can a JavaScript function be sent through a REST API using Node.js and Express?

I have a unique scenario where I need to send a custom JavaScript function as a response to a GET request made to an API endpoint. Currently, I am using Node.js with Express for my server implementation, but I am open to exploring other frameworks. When a ...

bing translator API: the variable text is translated with no content

I'm encountering an issue while working with javascript and PHP. The PHP code seems to run fine until it reaches the $curlResponse variable. From there onwards, all the subsequent variables ($xmlObj, $translatedStr, $translatedText) appear to be empty ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Tips for handling uncaught exceptions in Internet Explorer

In both Chrome and Firefox, it is possible to suppress exceptions, but unfortunately, this is not the case with Internet Explorer (IE). window.addEventListener("error", function errorHandler(event) { console.log("exception should be suppressed and not ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

Looking to organize my divs by data attributes when clicked - how can I achieve this with javascript?

I am looking to implement a dropdown sorting functionality for multiple divs based on different data attributes such as price and popularity. The specific divs are labeled as "element-1" and are contained within the "board-container". var divList = $(". ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...