I am trying to find the first location (or set of locations) in an array that is distinctly different from the initial location. The difference is determined based on a function calculating their distance. Here's an example array:
[
{lat: 45, lng: 45}, // 1st Location
{lat: 45.01, lng: 45.01}, // 1st Location
{lat: 55, lng: 55}, // 2nd Location - MATCH
{lat: 55.01, lng: 55.01}, // 2nd Location - MATCH
{lat: 54.99, lng: 54.99}, // 2nd Location - MATCH
{lat: 55, lng: 55}, // 2nd Location - MATCH
{lat: 65, lng: 65}, // 3rd Location
{lat: 65.01, lng: 65.01} // 3rd Location
]
In this example, the result should only contain the 2nd locations as they match within 0.2 latitude and longitude units.
My current approach involves:
- Fetching the initial location
- Iterating through the remaining locations and slicing the array from the index of the first different location
- Removing all subsequent locations that are not the same as the second location encountered
Here's the rough implementation:
var locations = [
{lat: 45, lng: 45},
{lat: 45.01, lng: 45.01},
{lat: 55, lng: 55},
{lat: 55.01, lng: 55.01},
{lat: 54.99, lng: 54.99},
{lat: 55, lng: 55},
{lat: 65, lng: 65},
{lat: 65.01, lng: 65.01}
];
const startingLocation = locations.splice(0,1)[0];
const first = locations.findIndex(location => {
const { lat, lng } = location;
return newLocation(startingLocation.lat, startingLocation.lng, lat, lng);
});
const validLocations = locations.slice(first);
const newLatLng = validLocations[0];
const last = validLocations.findIndex(location => {
const { lat, lng } = location;
return newLocation(newLatLng.lat, newLatLng.lng, lat, lng);
});
if (last > -1) {
validLocations.splice(last);
}
console.log(validLocations)
// Helper function to test if locations are the same
// For demo purposes only
function newLocation(lat1, lng1, lat2, lng2) {
return Math.abs(lat1 - lat2) + Math.abs(lng1 - lng2) > 1
}
This method involves multiple loops and may be hard to follow. Is there a way to simplify this while improving time complexity and clarity?