arranging objects based on the distance between them

Here is a JSON array I am working with:

var details = [
{
    'address':'Pantaloons,701-704, 7th Floor, Skyline Icon Business Park, 86-92 Off A. K. Road,Marol Village, Andheri East,Mumbai, Maharashtra 400059',
    'lat':'19.099910',
    'lng':'72.915373',
    'time':'NA',
    'sex':'Unisex',
    'place':'mall'
    },
    {
    'address':'Garodia Shopping Centre,Ghatkopar East,Mumbai, Maharashtra 400077',
    'lat':'19.074185',
    'lng':'72.908169',
    'time':'NA',
    'sex':'Male',
    'place':'mall'
    },
    {
    'address':'EF Mall,Andheri,Rambaug, MHADA Colony 20, Powai,Mumbai, Maharashtra 400076',
    'lat':'19.119056',
    'lng':'72.901324',
    'time':'NA',
    'sex':'Male',
    'place':'mall'
    },
];

Within this array, there is a dynamic variable called details['distance'], which is calculated using the Haversine formula in the function getDistance().

var dist = getDistance(lt,lg,lat,lng);
details[i]['distance'] = dist;

The information from this array is displayed within a div, and I want to sort the list by distance.

for (i = 0; i < details.length; i++) {
    var add= details[i].address;
    var lat = details[i].lat;
    var lng = details[i].lng;
    var time = details[i].time;
    var latLng = new google.maps.LatLng(lat, lng);
    var Gender = details[i].sex;
    var type = details[i].place;
    var dist = getDistance(lt,lg,lat,lng);
    details[i]['distance'] = dist;
    document.getElementById('list').innerHTML +='<p><img src="'+type+'.png" style="float:left;margin-right:5;"><div id="address"> ' + add +'</div><br><img style="height:30;float:right;" src="'+Gender+'.png" title="+Gender+"><a class="review" href="#">See Reviews</a>'+'<img style="float:right;margin-top:6;" src="write.png" title="Write a Review"><div id="time">Timings:'+ time +'</div>'+details[i].distance +'km'+'</p><hr/>';

    }

My sorting implementation looks like this:

details.sort(function(a,b) { return parseFloat(a.distance) - parseFloat(b.distance) } );

Although this sorts the values by distance, it sometimes displays incorrect details such as address and type after sorting. The entire array needs to be sorted without mixing up the other details.

Answer №1

var people = [
        { first_name: 'Lazslo', last_name: 'Jamf'     },
        { first_name: 'Pig',    last_name: 'Bodine'   },
        { first_name: 'Pirate', last_name: 'Prentice' }
    ];
for(var x=0; x<people.length; x++){
    people[x]['distance'] = people[x]['last_name'];

}
function sortByName(a,b) {
  if (a.distance < b.distance)
     return -1;
  if (a.distance > b.distance)
    return 1;
  return 0;
}
people.sort(sortByName);
alert(JSON.stringify(people)); 

output:

[{"first_name":"Pig","last_name":"Bodine","distance":"Bodine"},{"first_name":"Lazslo","last_name":"Jamf","distance":"Jamf"},{"first_name":"Pirate","last_name":"Prentice","distance":"Prentice"}]

See the live demonstration

Answer №2

It's a bit tricky to give you an answer because the array you provided does not contain a distance property, as pointed out by birdspider. However, your method should still work. You can test it in the console.

var details = [{'distance':'24.1','b':99},{'distance':'-12.5','b':100},{'distance':'35.6','b':101}]
details.sort(function(a,b) { return parseFloat(a.distance) - parseFloat(b.distance) } )

After sorting, if you check the details variable again, it will show:

[{'distance':'-12.5','b':100},{'distance':'24.1','b':99},{'distance':'35.6','b':101}]

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

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

What could be causing JavaScript Ajax calls to fail over SSL specifically on IOS devices, with the exception of IOS

I am encountering an issue with a mobile application I have developed. It makes an ajax xmlHttpRequest request over SSL to another application on the same domain in order to authenticate a user. Strangely, this call fails with response code zero on IOS dev ...

JSON failed to provide me with a complete format

I am currently working on creating a JSON object, but I'm facing an issue with the format. It seems to only include the first property of "User" and the last property "item," instead of providing me with the complete JSON structure. Any help or guidan ...

Obtain the complete path in Vue router by utilizing nested routes

After creating nested routes for Vue Router, I encountered a problem while using the routes to generate a navigation menu. Currently, I am using route.path in 'router-link :to=' which only gives me a part of the path. I want to include the absolu ...

Options menu in an Android Studio application

Having just begun my journey with Android Studio, I am facing difficulties in creating a menubar. Despite my efforts to find solutions, none of them seem to work out. I attempted the following code snippet, but I feel stuck at this point: public class Ma ...

Customizing container response for spring-security BadCredentialsException

I am working on a simple REST application that requires certain resources to be secured with HTTP Basic authentication. I want to ensure that no container-generated HTML is returned in response to any client actions. To achieve this, I have configured my S ...

Encountering a TypeError with Arg 1 while trying to execute the save method in jsPDF

I am currently working on a react project with a simple implementation of jsPDF. I am trying to execute the sample 'hello world' code but encountering an error when using the save method: https://i.stack.imgur.com/o4FWh.png My code is straightf ...

Utilizing the malloc function to dynamically allocate memory for an array

My current challenge involves creating an array of structs using malloc to properly allocate the necessary memory. Here is my code snippet: typedef struct stud{ char stud_id[MAX_STR_LEN]; char stud_name[MAX_STR_LEN]; Grade* grd_list; Income* i ...

Issues with Jquery Autocomplete feature when using an Input Box fetched through Ajax requests

When a user selects an option from the drop-down list, an input box is dynamically added to the page using AJAX. document.getElementById("input_box").innerHTML ="<input id='ProjectName'/>"; However, there seems to be an issue with jQuery ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

Encountering issues with parsing JSON data following its transmission through an Ajax request

Client Side Once an object has been processed with JSON.stringy, it is sent in this format to a node-server via a POST request: {"id":"topFolder","parentPath":null,"name":"newProject","is":"root","children":[]} The request is sent from the client side u ...

When a cursor hovers over an image, a dark line appears

I wanted to create a hover effect where the image would enlarge when hovered over. I achieved this using a JavaScript function that applies the transform property with a scale of 1.2 to the picture. However, during the animation, a black line appears at th ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

Starting Web Server using File (file://) protocol

I'm currently using Quasar to develop a Vue SPA web app/page. For this project, the web app will only run by clicking on the index.html file generated by the Quasar packager. This package will not be distributed online or hosted on any domain. My mai ...

Issue with Express - Session not persisting across consecutive SSE requests

Currently, I am delving into Server-sent Events using Node.js and Express. I have successfully set up request handling and stream writing, but I am facing challenges with session management. The session does not persist between subsequent calls. Snippet o ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

The div element disappears upon calling the load() function

Currently, I am working to implement sorting criteria (such as by price or author) on my jsp page. I am utilizing ajax to refresh the content of a div when a new sorting option is selected. However, upon calling the reload function, the div just disappears ...

What is the process for uploading an image and entering text into the same row in Google Sheets?

Hello, I am currently working on a Google Script web app that enables users to upload 10 photos along with comments for each photo. This information will then be inserted into a Google Sheet when the user clicks the 'upload' button on the web app ...

Is there a pure JavaScript solution to replace jQuery's .prev() function?

Looking for a JavaScript alternative to this jQuery code: $(".q-block-container").prev(".sub-block-container").css("border-bottom","none"); I am seeking a pure JavaScript solution that selects the previous sibling ONLY if it matches a specific selector ( ...

Is there a way to repair my CSV file with nested JSON objects contained within each cell?

I have successfully written code that exports data into json-like formats in a csv file. Here is the snippet of my PowerShell script: Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1" @initParams # Site configuratio ...