I have an array which contains key-value pairs. Keys are (ID, Lat, Lon).
What I am trying to do is compare current element ID with next element ID and if they are equal put the Lat and Lon of the current element in an object (in my case "point") and call a function (InjectIntoArray on that point which initializes a global array points[]).
When condition becomes false (i.e current id not equals next id), in else part I am putting the current elements Lat and Lon in a object and calling a function on that one, this is because the ID of next element is going to be different and I have to get all the Lat and Lon of current element ID.
The problem occurs when the last element is being checked, it exits without obtaining the last record.(i.e list[lastElement]).
How can I get the Lat and Lon of all elements? Is there any better way to achieve this?
Here is my array -
var list = [
{ id: 100, Lat: 19.25, Lon: 74}, { id: 100, Lat: 19.79, Lon: 74.19 },
{ id: 101, Lat: 19.99, Lon:75.10 }, { id: 101, Lat: 20.37, Lon:68.9},
{ id: 119, Lat: 17, Lon: 70 }, { id: 107, Lat: -16, Lon: -165 },
{ id: 107, Lat: -15, Lon: -150 }
];
And the code-
for (let i = 0; i < list.length - 1;i++) {
if (list[i].id == list[i+1].id) {
var point = { LATITUDE: list[i].Lat, LONGITUDE: list[i].Lon };
InjectIntoArray(point);
}
else {
var point = { LATITUDE: list[i].Lat, LONGITUDE: list[i].Lon };
InjectIntoArray(point);
plotRoute(false,2);
points = [];
}
}
I think, the best here is to use the reduce function:
var list = [ // list from the example in original question
{ id: 100, Lat: 19.25, Lon: 74}, { id: 100, Lat: 19.79, Lon: 74.19 },
{ id: 101, Lat: 19.99, Lon:75.10 }, { id: 101, Lat: 20.37, Lon:68.9},
{ id: 119, Lat: 17, Lon: 70 }, { id: 107, Lat: -16, Lon: -165 },
{ id: 107, Lat: -15, Lon: -150 }
];
allRoutes = list.reduce(function(routes,e){
if (!routes[e.id]) routes[e.id] = [];
routes[e.id].push({LATITUDE: e.Lat, LONGITUDE: e.Lon});
return routes;
}, {})
this way you get an object with all "routes" assigned to their IDs.
{
100: [{ "LATITUDE": 19.25, "LONGITUDE": 74 },
{ "LATITUDE": 19.79, "LONGITUDE": 74.19 }],
101: [{ "LATITUDE": 19.99, "LONGITUDE": 75.1 },
{ "LATITUDE": 20.37, "LONGITUDE": 68.9 }],
107: [{ "LATITUDE": -16, "LONGITUDE": -165 },
{ "LATITUDE": -15, "LONGITUDE": -150 }],
119: [{ "LATITUDE": 17, "LONGITUDE": 70 }]
}
Now you can iterate over the routes and plot them one by one, for example in the following way:
plotRoute = function(r){ console.log('plotting route: ', r) }
Object.values(allRoutes).map(plotRoute)
Cheers, iPirat