I am trying to sort my locations array from shortest to longest distance with the following code:
for(var i=0; i<locations.length;i++)
{
var swapped = false;
for(var j=locations.length; j>i+1;j--)
{
if (locations[j]['distance'] < locations[j-1]['distance'])
{
var temp = locations[j-1];
locations[j-1]=locations[j];
locations[j]=temp;
swapped = true;
}
}
if(!swapped)
break;
}
When I tried running the program, I get the following error in Firebug:
locations[j] is undefined
I console.logged the locations array and this is what it lloks like:
[Object { id="1", marker=U, more...}, Object { id="4", marker=U, more...}, Object { id="6", marker=U, more...}, Object { id="3", marker=U, more...}, Object { id="2", marker=U, more...}, Object { id="5", marker=U, more...}]
Is there a way to numerically index the objects, while keeping the objects’ data associatively indexed?
Or is there a way to access the ith+1 or ith-1 element if I have for resort to using this.distance in a foreach loop?
You started 1 to late, remember array keys are indexes, which start at 0
You’re going to run into a problem on the last loop so I added
if(locations[j-1]['distance'] ...