Discovering Consecutive Matching Positions in an Array

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:

  1. Fetching the initial location
  2. Iterating through the remaining locations and slicing the array from the index of the first different location
  3. 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?

Answer №1

The method you've implemented with two loops is both concise and effective. It remains unnecessary to alter anything in this solution. However, it would be wise to avoid excessively using slice and splice on arrays; instead, focus on determining the initial array's first and last index for your match - then perform a single slice operation at the end.

Your code can actually be further simplified:

const initialMatch = getIndexFrom(sourceList, notMatchingTo(sourceList[0]), 1);
if (initialMatch == -1) return [];
const followingMatch = getIndexFrom(sourceList, notMatchingTo(sourceList[initialMatch]), initialMatch + 1);
if (followingMatch == -1) return sourceList.slice(initialMatch);
else return sourceList.slice(initialMatch, followingMatch);

function notMatchingTo(targetVal) {
  return function(element) {
    return Math.abs(targetVal.x - element.x) + Math.abs(targetVal.y - element.y) > 1;
  };
}
function getIndexFrom(array, condition, startingIndex) { // it's unfortunate that the native `findIndex` doesn't support specifying a starting position like `indexOf`
  for (; startingIndex < array.length; startingIndex++)
    if (condition(array[startingIndex], startingIndex))
      return startingIndex;
  return -1;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate the form outside of normal business hours

I need to create a form for a delivery service that only operates from 9am to 9pm. If a user submits the form outside of these hours, I want to redirect them to a page displaying the company's operating hours instead of a thank you page. For instance ...

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

Retrieving information from a JSON file using React

Hello everyone, I'm currently working on creating a dynamic menu that pulls its items from JSON data. I am using React and struggling with the correct syntax. Here is the sample data: { "name": "menu", "childr ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

What is the best way to ensure that at least one of the two user inputs matches the specified regex pattern?

I am facing a challenge with regular expressions for zip codes from two different countries - The Netherlands and Belgium. For The Netherlands: .match(/^[1-9][0-9]{3} ?(?!sa|sd|ss)[A-Za-z]{2}$/g) For Belgium: .match(/^[1-9]{1}\d{3}$/g) Users should ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...

Turning PHP array into JSON using Zend RPC

Greetings, I am facing a small issue that I need help with. Currently, I am developing a RPC service using ZendFramework and Apigility which requires the response to be in a json array format. Below is the content negotiation code snippet that I have imple ...

Is there a way to prevent HTML rendering with Javascript within a JSP page?

When a user accesses our site from China, we need to block certain assets to optimize the speed of the site. For example, resources from Facebook need to be blocked from loading altogether. The challenge is that this task must be accomplished using JavaSc ...

Encountering an "invalid element type" error while attempting to add material-ui to a Next.js project

Hey there, I've been working on integrating Material UI into my Next.js project. I followed the example on Next Js GitHub as well as a helpful YouTube tutorial. Unfortunately, I encountered an error that reads: Error: Element type is invalid: expecte ...

Logic of bitwise operations

Is there a way to efficiently find all arrays that, when combined bitwise with array1, result in array2? Both arrays are equal-sized and contain only 0s and 1s. For example, if array1 = [1, 1, 1] and array2 = [1, 1, 1], the output should be eight arrays: [ ...

Determine whether any property within the object is currently null

I am working with an array of objects called data, each object in the array having multiple properties, some of which may have null values. https://i.sstatic.net/hc5O3.png My goal is to filter through this array and eliminate any object that contains a p ...

Is there a way to display the HTML input date by simply clicking on text or an image?

I need to display a date picker when I click on specific text or an image. I am working with reactjs and utilizing the HTML input type="date", rather than the React-datepicker library. Here is the code snippet: import { useRef } from "r ...

Improving Performance in Vue by Reducing `$set` Usage

Sharing my code snippet below <div v-for="namespace in chosenNamespaces" v-bind:key="namespace.id"> <!-- Select the Parameter --> <select @change="updateParameter($event, namespace.id)" v-model="currParameterValues[na ...

Creating a three-dimensional array in Numpy using a one-dimensional array

If a 1D array called A is provided, is there a straightforward method to create a 3D array named B, where each value B[i,j,k] equals the corresponding element from A[k]? It can be assumed that the dimensions of B are predetermined, and that B.shape[2] = ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Displaying an element as a dropdown menu on PrimeVue

I have a challenge with rendering a Dropdown using PrimeVue with the given script: <template lang="pug"> Dropdown#tag(v-model="tag" :options="tags") </template> <script setup> import axios from 'axios&a ...

What is the process for integrating an image from a byte array alongside additional content in CodeIgniter?

I am currently facing an issue with displaying a user's profile view using an image from a byte array. While I have successfully rendered the image, I am struggling to integrate it with other profile content due to the header('Content-Type: image ...

Mastering the BFCache management in React for optimal performance

Before redirecting to an external payment provider, I display a loading screen to account for longer load times. If the user decides not to complete the payment and navigates back using gestures or the browser's back button, the page is pulled from t ...

Could someone explain why the window.onload function is not functioning as expected on my other Vue page?

I am facing an issue with my two pages or "views" that have identical JS code. Both pages have a window.onload function where I perform some actions: console.log("loading") window.onload = function() { console.log("loaded") // do stuff } The problem is t ...