Folky.H Folky.H -4 years ago 28
Javascript Question

JavaScript - Organize array in a particular way

I have the below array of coordinates:

var coords = [35.77204705542798, -5.815865197320899, 35.77205120747819, -5.815754188240848, 35.77197468036722, -5.815810097181759, 35.77201185726312, -5.816182008817898, 35.77188028308802, -5.816782866625928, 35.77144809183601, -5.817054836919457, 35.77130127311978, -5.817231221149015, 35.77121654704168, -5.817323279458099, 35.77197602552531, -5.818491135420929, 35.77211527443405, -5.818831898394636, 35.77220613582161, -5.819054426882189, 35.77225761824354, -5.819182167400329, 35.77557809840525, -5.819685065789988, 35.77522352494348, -5.821346612263469, 35.77815743782872, -5.822735160242799, 35.77863231735067, -5.822959942846667, 35.77915215012052, -5.823206036666789, 35.77917987363854, -5.82321907562955, 35.77913908191616, -5.825751400638378, 35.77947725976961, -5.826044519616627, 35.77923063670355, -5.82893344672563, 35.77920722271806, -5.829544463218058, 35.77924325929096, -5.82965650991142, 35.77913169320556, -5.830906964998152, 35.77917349450947, -5.830173084585434, 35.78563643141488, -5.829373128632887, 35.7859055726137, -5.829317961099034, 35.78659089504106, -5.829249272155759, 35.78704770052305, -5.829163948962961, 35.78696081760869, -5.829114610331397, 35.78687737614365, -5.829067226012621, 35.78679073445069, -5.829018024365507, 35.78661289235281, -5.828929232334034, 35.78652027010703, -5.828884857172518, 35.78643576729606, -5.828844387274908, 35.78635159916791, -5.828804167105649, 35.7862672257822, -5.828763857888811, 35.7872100444153, -5.866787159467321]


Basically, the order is like the following
([lat,lng,lat,lng........])


var waypts = [];

//should execute for loop here, get lat and lng from the array
stop = new google.maps.LatLng(lat, lng)
waypts.push({
location: stop,
stopover: true
});
///


I've tried the below, but it seems to run only once

for(var i=0; i<=coords.length; i++){
//get only even so I can have something like coords.slice(0,2), coords.slice(2,4)
if ((i % 2) == 0){
coords.slice(i+0,i+2)
}
}


The final result that will be run on the background should be similar to:

stop = new google.maps.LatLng(35.77205120747819, -5.815754188240848)
waypts.push({
location: stop,
stopover: true
});

stop = new google.maps.LatLng(35.77197468036722, -5.815810097181759)
waypts.push({
location: stop,
stopover: true
});

Answer Source

You could just iterate over every pair :

for(var i=1; i<coords.length; i+=2){
  var lat=coords[i-1],long=coords[i];

 stop = new google.maps.LatLng(lat, lng)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download