Locate the nearest index within the array

I'm currently working with an array of "events" where the key assigned to each event corresponds to the Unix Timestamp of that particular event. To illustrate, consider the following array of event objects in JS:

var MyEventsArray=[];
MyEventsArray[1513957775]={lat:40.671978333333, lng:14.778661666667, eventcode:46};
MyEventsArray[1513957845]={lat:40.674568332333, lng:14.568661645667, eventcode:23};
MyEventsArray[1513957932]={lat:41.674568332333, lng:13.568661645667, eventcode:133};
and so forth for many rows...

The data is transmitted via an Ajax call and encoded in JSON to be processed using JS. Upon receiving the dataset, if I have a Unix Timestamp such as 1513957845 from another source and need to identify the event corresponding to that time stamp... it's pretty straightforward by simply selecting the element from the array with the matching index (the one second in the list above). Now here's the dilemma: what if the specified index isn't found (let's say we're searching for UXTimestamp=1513957855) and this index doesn't exist within the array? In such cases, I aim to retrieve the event with the closest index (in our example, MyEventsArray[1513957845] would be chosen since its index, 1513957845, is the nearest to 1513957855). How can I achieve this desired outcome? My challenge lies in managing array indexes particularly when I receive the array without knowing the starting point of the index.

How does the system handle scenarios like this? Does the machine allocate memory, potentially wasting space, for vacant/dummy elements interspersed throughout the rows or does the compiler possess mechanisms to construct its own index and optimize storage efficiency? Essentially, is it safe to manipulate indexes as we are currently doing, or would it be better to initialize the array as follows:

var MyEventsArray=[];
MyEventsArray['1513957775']={lat:40.671978333333, lng:14.778661666667, eventcode:46};
MyEventsArray['1513957845']={lat:40.674568332333, lng:14.568661645667, eventcode:23};
MyEventsArray['1513957932']={lat:41.674568332333, lng:13.568661645667, eventcode:133};
and so on for thousands of entries...

In this setup, the key and index are distinctly separate allowing us to access the first element using MyArray[0] even if the specific key value is unknown. Is this alternative approach more resource-intensive (since both index and key must be stored), in terms of memory usage, or do the implications remain unchanged for the compiler?

Answer №1

When looking at MyEventsArray[1513957775] compared to MyEventsArray['1513957775'], they are essentially the same. This is because array indexes are essentially just property names, which are treated as strings.

As for concerns about sparse indices leading to a large number of empty cells being allocated, rest assured that this will not occur. Sparse arrays only store the values that are actually assigned to them, without wasting space on empty elements.

To quickly find a specific key within the array, one approach is to get an array of keys, sort them, and then locate the desired key:

var MyEventsArray=[];
MyEventsArray[1513957775]={lat:40.671978333333, lng:14.778661666667, eventcode:46};
MyEventsArray[1513957845]={lat:40.674568332333, lng:14.568661645667, eventcode:23};
MyEventsArray[1513957932]={lat:41.674568332333, lng:13.568661645667, eventcode:133};

var target = 1513957855;

var closest= Object.keys(MyEventsArray)
                   .map(k => ({ k, delta: Math.abs(target - k) }))  
                   .sort((a, b) => a.delta - b.delta)[0].k;

console.log(closest);

Answer №2

If you want to efficiently exit an iteration when the delta exceeds a certain threshold, you can use Array#some.

var array = [];
array[8937458761] = { lat: 40.671978333333, lng: 14.778661666667, eventcode: 46 };
array[8937458835] = { lat: 40.674568332333, lng: 14.568661645667, eventcode: 23 };
array[8937458922] = { lat: 41.674568332333, lng: 13.568661645667, eventcode: 133 };

var key = 0,
    search = 8937458855;

Object.keys(array).some(function (k) {
    if (Math.abs(k - search) > Math.abs(key - search)) {
        return true;
    }
    key = k;
});

console.log(key);

Answer №3

If you want to retrieve an array of keys from MyEventsArray, you can utilize Object.keys(MyEventsArray). The keys in this array are represented as strings, so you will need to iterate through them to find the closest match.

var MyEventsArray=[];
MyEventsArray[1513957775]={lat:40.671978333333, lng:14.778661666667, eventcode:46};
MyEventsArray[1513957845]={lat:40.674568332333, lng:14.568661645667, eventcode:23};
MyEventsArray[1513957932]={lat:41.674568332333, lng:13.568661645667, eventcode:133};
Object.keys(MyEventsArray)

["1513957775", "1513957845", "1513957932"]

You can refer to the official Mozilla documentation on Arrays in JavaScript for more information.

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

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

Transferring variables from EJS to JavaScript on render (server to client) securely to prevent cross-site scripting vulnerabilities

When passing variables to JavaScript using ejs, the accepted method often looks like this: <script> var foo = <%- JSON.stringify(foo) %>; </script> However, there have been issues with XSS vulnerabilities using this approach. Is there ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

Achieving a Full-Screen Three.js Canvas in React: A step-by-step guide on spanning the view height and width of a webpage

I've been working on tweaking the code found in this particular example: How to connect Threejs to React? This is the snippet of code I am focusing on: import React, { Component } from 'react' import * as THREE from 'three' clas ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Send the JSON output to the controller function

Hello there! I am new to asp.net mvc and I'm looking for a way to pass JSonResult data to a controller method. In my View, I have set up a table like this: <table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-respo ...

Shortcut for JSON formatting in Sublime Text

I prefer using SublimeText for coding. Is there a quick way to reindent JSON code in SublimeText? I've successfully installed Package Control and it's functioning properly. I attempted to use the JsonReindent package, but couldn't find a ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

Encountered an error while handling a promise: Unable to access null properties (specifically, 'useState')

I'm having trouble understanding why I keep encountering this error with the line const [isLoading, setLoading] = useState(true);. It's initially set to true so it shouldn't be undefined. export default async function GetProducts() { c ...

Customized validation message in Angular Formly with live data

I'm currently working with angular-formly and attempting to create a validation that checks if the user input falls within a dynamically set range of two numbers. I thought the simplest way to achieve this was by using a few variables, and while the v ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

What is the best way to include a dictionary within an already existing JSON dictionary in Python?

Check out this sample dictionary: It is stored in a JSON file: { "fridge": { "vegetables": { "Cucumber": 0, "Carrot": 2, "Lettuce": 5 }, "dr ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

Tips for extracting data from nested JSON structures

I'm trying to retrieve the username of a user from the Firebase Realtime Database, which is stored in a UsersList. I have attempted various methods as shown in the code snippets below: https://i.stack.imgur.com/GsovS.png However, no matter what I tr ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

What is the best way to trigger a re-render in a child component in React using forceUpdate

Is there a way to force reload a child component in React, similar to using this.forceUpdate() for a parent component? For example, consider the following scenario: buttonClick = () => { // This updates the parent (this) component this.forceUpda ...

Tips for extracting information from a JSON response

I'm currently extracting data from a json response, which has the following format. My goal is to retrieve the "recipient" dictionary and display it in a table where each cell contains the name, unique id, and image. How can I extract this dictionary ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...

The Firebase function that reloads the auth currentUser is not refreshing properly within a Vue component

My function for updating the profile URL using the reload method is not reflecting changes in my computed property. Computed Property computed: { photoUrl: function() { return firebase.auth().currentUser.photoURL; }, } Function onFileC ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...