I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so:
<script type="text/javascript">
coordinates = {{ coordinates | safe}}
</script>
These coordinates contain a field called country.
To organize these objects, I use the following sorting method:
coordinates.sort(sortByCountry);
This is my custom sortByCountry function:
function sortByCountry(x, y) {
return ((x.fields.country == y.fields.country) ?
0 : ((x.fields.country > y.fields.country) ? 1 : -1 ));
}
When I run
coordinates.sort(sortByCountry);
, it correctly orders the objects.
However, when I loop through the coordinates array, it seems as if the sorting did not take effect. For each country, I create a new array and group all coordinates belonging to that country together in that array. All of these arrays are nested within another array named countries.
var countries = [];
var counter = 0; // number of countries
function sortByCountry(x, y){
return ((x.fields.country == y.fields.country) ? 0 : ((x.fields.country > y.fields.country) ? 1 : -1 ));
}
function country_assignment(){
coordinates.sort(sortByCountry); // ****This works returns a sorted coordinates list, can even do window.coordinates and get the sorted list
countries.push(new Array());
countries[counter].push(coordinates.pop());
length = coordinates.length;
for( var l = 0; l < length; l++){
//this loops through coordinates as if it was not sorted
if((countries[counter][0].fields.country == coordinates[0].fields.country)){
countries[counter].push(coordinates.pop());
} else {
countries.push(new Array());
counter = counter + 1;
countries[counter].push(coordinates.pop());
I have attempted
coordinates = coordinates.sort(sortByCountry);
But this approach also does not produce the desired result.
Here is an example of the JSON objects structure:
<script type="text/javascript">
coordinates = [{"fields": {"latitude": 38.5512238, "country": "USA", "location": "802 D St, Davis, CA 95616, USA", "longitude": -121.7441921, "visited": true}, "model": "mapper.destination", "pk": 1}, {"fields": {"latitude": 51.501009, "country": "Britian", "location": "London SW1A 1AA, UK", "longitude": -0.1415876, "visited": true}, "model": "mapper.destination", "pk": 2}, {"fields": {"latitude": 51.501009, "country": "Britian", "location": "London SW1A 1AA, UK", "longitude": -0.1415876, "visited": true}, "model": "mapper.destination", "pk": 3}, {"fields": {"latitude": 13.7524008, "country": "Thailand", "location": "Na Phra...
</script>