Sorted Array Resulting from Execution of For Loop

My goal is to calculate the distance between two sets of latitude and longitude coordinates using the npm geolib library. I have a function that queries Firestore and retrieves an array of objects. Within this array, I iterate through each object in a for loop and use the geolib.getPreciseDistance method to calculate the distance.

The challenge I am facing is sorting the resulting array from the for loop. Ideally, I would like the new array to be sorted with the object closest in distance at index[0].

I have included my current progress below. Any feedback or guidance would be greatly appreciated as I continue to learn. Thank you!

function getNearestWalk() {
  let currentLng = userLocation.longitude;
  let currentLat = userLocation.latitude;
  firestore()
    .collection('Walks')
    .where('status', '==', 'started')
    .limit(10)
    .get()
    .then((walks) => {
      const walksArray = [];
      walks.forEach((liveWalks) => {
        walksArray.push(liveWalks.data());
      });
      console.log(walksArray);

      for (var i = 0; i < walksArray.length; i++) {
        geolib.getPreciseDistance(
          { latitude: currentLat, longitude: currentLng },
          {
            latitude: walksArray[i].latitude,
            longitude: walksArray[i].longitude,
          }
        );
      }
    });
}

Answer №1

Based on the information provided in response to @Elnatan, it seems like you are looking for an array of objects that represent coordinates sorted by shortest...furthest distance

An approach that is simple (without considering complexity) is as follows:

  • First, create a utility function called calculateDistance that takes an object and performs the necessary logic using geolib.getPreciseDistance, returning its value.
  • Next, assign a variable to the result of:
    walksArray.sort( (a, b) => calculateDistance(a) - calculateDistance(b) )
  • Finally, return the sorted array.

In my opinion, it would be beneficial to separate tasks in your #getNearestWalk method for better organization and include a helper function to handle fetching walks effectively with proper error handling using try {} catch {} as asynchronous calls may not always succeed.

Please let me know if this solution meets your requirements!

Answer №2

Within the initial code, the variable walks represents a querySnapshot. The primary task is to extract data from the documents. This specific function conducts the query and retrieves the data from the docs...

function initiateWalks() {
  return firestore()
      .collection('Walks')
      .where('status', '==', 'started')
      .limit(10)
      .get()
      .then(querySnapshot => querySnapshot.docs.map(d => d.data()));
}

This particular function includes adding the distance from a specified point to the doc data...

// assigning the distance from a particular position to each doc in the array of docs
function calculateDistances(docs, position) {
  return docs.map(doc => {
    const docPosition = { latitude: doc.latitude, longitude: doc.longitude };
    const distance = geolib.getPreciseDistance(position, docPosition);
    return { ...doc, distance }
  })
}

Subsequently, composing getNearestWalk() becomes straightforward...

function findClosestWalk(position) {
  return initiateWalks().then(docs => {
    docs = calculateDistances(docs, position)
    return docs.sort((a, b) => a.distance - b.distance)
  });
}

Implement this by following these instructions...

findClosestWalk(userLocation.latitude, userLocation.longitude).then(array => {
  // the array will contain doc data ordered by proximity from userLocation
})

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

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...

What is the best way to resume a Jquery function if it has not

How do I make my form alert re-trigger when the user clicks the button again if the input is still empty? What I've tried: After clicking the button, it checks if the inputs are empty and shows an alert. However, once the alert appears, if I click th ...

Is it considered fundamentally inappropriate to call $scope.$digest within $scope.$on?

I recently inherited some AngularJS code, and my knowledge of both the codebase and Angular itself is limited. Within the code I inherited, there are instances where $scope.$digest is being called inside a $scope.$on method within a controller. Here's ...

"Upload a text file and create a JavaScript variable that contains the text within it

I am currently developing a library and I need to add a feature that reads the contents of a text file. Currently, it only returns the path. How can I modify it to return the actual content of the file? function displayFileContent() { var file = do ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

Challenges with an array of hash references in Perl

In one of my project functions, I have the following code snippet: sub get_src_info($) { my $package = shift; my ($key,$value,$tail) =("","",""); my (@APT_INFO,$r); open APT, "apt-cache showsrc $package|"; while ( ...

Ways to retrieve onclick value using JavaScript

Imagine if my website contains the following code: <a href="" onclick="lol(222)"> <a href="" onclick="lol(223)"> <a href="" onclick="lol(212)"> <a href="" onclick="lol(122)"> Now, I want to extract all the values inside the lol() ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

Pairing Symfony2 with the power of jQuery AJAX

When developing an application with Symfony2 and using Jquery as a JavaScript FW along with Twig templates, I encountered the need to pass selected tag values from the template back to the controller upon submission. After rendering a template from the con ...

Tips on eliminating the letter 'X' from a text/search input field in HTML

There are various solutions available for removing the "X" from an input field in IE 10+ browsers. I have tried multiple approaches without success. For example, I have referenced: ans 1 ans 2 ans 3 Despite implementing all of these solutions, I still ...

What are the methods to transmit various data formats in an AJAX POST request?

I am facing an issue with sending a JSON object along with two file upload objects to the controller in JavaScript. I have tried the following code snippet: data: {"jsonString":jsonString, "fd":"fd", "fd1":"fd1"}, Is there any other way to achieve this, ...

Django issue: A Tuple or struct_time argument is necessary

Currently, I am developing a code that deals with 2 variables - showdate and viewtype. Both of these variables are transferred via JavaScript using the POST method. viewtype = send an srt showdate = send a date from javascript Within this code snippet, ...

Harmonizing various client viewpoints in a ThreeJS scene featuring a unified mesh structure

I am fairly new to ThreeJS and I am curious to know if it is possible to achieve the following, and if so, how can it be done: Two web browser clients on separate machines want to load the same html-based Scene code, but view it from different perspective ...

Duplicate the array of objects and make alterations without affecting the original array

I have an array of objects that I need to deep copy and make modifications to each object without altering the original array or its contents. Here is my approach in JavaScript, but I am open to suggestions on a better method. const users = [ { ...

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

Updating JSON in JavaScript

I am striving to structure a JSON object in the following manner: {"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0 ...

Is there a way to change the font size with a click in JavaScript or Angular?

Here is a breakdown of the 4 steps: 1.) Begin by clicking on a category 2.) The filtered products will be displayed 3.) Select the desired products from the filter 4.) Once selected, the products will appear in the rightmost part of the screen within t ...

Error in Vue class-based component: Unable to access property 'message' due to its value being null

I am currently exploring the combination of typescript and Vue for the first time in my project. I am encountering an issue that seems to be related to scope, but I could be mistaken. I referenced a small example from VueJS and adapted it as shown below: ...

The issue with AngularJS ng-model not functioning properly with dynamically generated input fields

I have set up a dynamic templateUrl for form fields and I am attempting to use ng-model within ng-repeat. The parent directives and form field directive are functioning correctly and being generated, but when I try to apply ng-model it does not seem to wor ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...