Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object.
So far, I have been successful in listing and sorting the items by string values and test integers like latitude. The sorting functionality is working correctly.
Below is the JSON code for parks:
[
{
"name": "Greenhead Park",
"latitude": 53.648748,
"longitude": -1.796985,
"image": "Greenhead_Park.jpg"
},
{
"name": "Shibden Park",
"latitude": 53.730610,
"longitude": -1.838229,
"image": "Shibden_Park.jpg"
},
{
"name": "Beaumont Park",
"latitude": 53.625146,
"longitude": -1.809171,
"image": "Beaumont_Park.jpg"
}
]
However, my current challenge is sorting the items by distance. Unfortunately, the JSON file does not include a 'distance' element in the items. To resolve this, I am utilizing the Google Maps API - Geocode to calculate the distance between the user's location and the park's location.
In a for loop, I am adding a new 'distance' element to each item:
parks[i]["distance"] = distance;
Despite successfully adding the distance to the object, when I attempt to reference it by console.logging(a.distance), it returns as undefined.
This issue arises after temporarily adding an element to each item in the JSON object. Although it appears defined when logging the object, referencing it results in 'undefined.'
If any suggestions or insights are available, your help would be greatly appreciated.
EDIT: For clarification, here is the function that sorts the object:
function sortParks(parks,sortMethod){
parks.sort(function(a, b){
console.log(parks);
console.log(a.name);
console.log(a.distance);
if(sortMethod == "az") return (a.name > b.name) ? 1 : (a.name < b.name) ? -1 : 0;
else if(sortMethod == "za") return (a.name < b.name) ? 1 : (a.name > b.name) ? -1 : 0;
else if(sortMethod == "dc") return a.distance - b.distance;
else if(sortMethod == "df") return b.distance - a.distance;
else alert("There was an issue identifying the sort type");
});
return parks;
}
The problem pertains to 'distance' being undefined when console.logged. While 'name' displays properly, attempting to access 'distance' results in 'undefined.'