The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as -

['2011-04-26', '2011-05-02', 'Week 1', '2010 - 11']
...

The objective is to assign a week number to each timestamp in the records. While a traditional linear search could achieve this, it becomes cumbersome when dealing with over 10,000 JSON records and nearly 300 weeks in the calendar.

Any suggestions on a more efficient approach?

Additional note: The reason for needing the calendar is that the weeks mentioned are not based on the actual week of the year but rather defined elsewhere.

Would there be a more effective method if the strings were converted to Date.getTime()?

Answer №1

If we only have 300 weeks to work with, one effective strategy would be to create an intermediary lookup object that matches each possible timestamp to its corresponding week number. By running a basic loop, you can generate something like this:

{
    '2011-04-26': 1,
    '2011-04-27': 1,
    // ...
    '2011-05-02': 1,
    '2011-05-03': 2,
    '2011-05-04': 2,
    // ...
}

These values would serve as references in your calendar array.

With this lookup object in place, you can easily assign your 10,000 records to their respective calendar weeks by performing a quick search in this object.

Answer №2

If your calendar records are organized in some manner, you can implement a binary search algorithm on them. Consider saving the dates as timestamps instead of strings to potentially speed up comparisons (although string comparison works fine for the current format).

An alternative approach could be to index your calendar by "weeks". For example:

{
  "Week 1": ['2011-04-26', '2011-05-02', '2010 - 11'],
  "Week 2": ['2011-05-03', '2011-05-09', '2010 - 12'],
  ...
}

It's worth noting that creating this lookup object from your calendar array is an O(n) operation. Therefore, if you only need to search for one record, even a linear search on the original array might be faster.

Below is a sample algorithm for searching in your original array:

var calendar = [
  ['2011-04-26', '2011-05-02', 'Week 1', '2010 - 11'],
  ['2011-05-03', '2011-05-09', 'Week 2', '2010 - 12'],
  ...
];
function getRecord(date) {
    var l = 0,
        r = calendar.length-1;
    while (l <= r) {
        var m = ~~(l + (r-l)/2);
        var comp = comparefn(this[m]);
        if (calendar[m][1] < date)
            l = m+1;
        else if (calendar[m][0] > date)
            r = m-1;
        else
            return calendar[m];
    }
    // If a date falls between two weeks in the calendar, behavior may vary
    return null;
}

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

When the time comes, ReactDOM will render your element into the designated container,

What does the [,callback] parameter represent in the ReactDOM.render(element, container) method? ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

"An ActionResult is received as null when the model is passed as an

Has anyone encountered a situation where the model is null when passed to the controller? I inserted an alert in the ajax call to verify the value and it seemed correct, but upon debugging on the first line of the controller's ActionResult, it shows a ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

JavaScript counter that starts at 1 and increments with each rotation

I am working with an array of image IDs. let images = ['238239', '389943', '989238', ... ]; let max = images.length; The array begins at index 0 and its size may vary. For instance, if there are 5 images in the array, the i ...

Ensure to verify the `childProperty` of `property` within the `req.checkBody

When working with Node.js, a common practice is to use code like the following: req.checkBody('name', 'Group name is required.').notEmpty(); In a similar fashion, I have implemented something along these lines: req.checkBody('pa ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

"Exploring the Power of Vue 3 Event Bus Through the Composition API

I recently set up mitt and I'm facing difficulties dispatching events to another component. The issue arises due to the absence of this in the setup() method, making it challenging to access the app instance. Here's my current approach: import A ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

Purge React Query Data By ID

Identify the Issue: I'm facing a challenge with invalidating my GET query to fetch a single user. I have two query keys in my request, fetch-user and id. This poses an issue when updating the user's information using a PATCH request, as the cach ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Looking for a character that includes both lowercase and uppercase letters

Here is the JSON data I have: [ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] var searchBarInput = TextInput.value; var ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...

Storing JSON data in an array using JavaScript is a powerful method to

Here is an example of JSON data: [{ "address": "A-D-1", "batch": [{ "batch_number": "B-123", "cost": [{ "cost": "C1" }] }] }, { "address": "A-85-1", "batch": [{ "batch_number": "B-6562", ...

In JavaScript, the JSON Object only stored the final result from a loop

I am currently working on an HTML Site that features 4 inputRange sliders. My goal is to store all values from these sliders in a nested JSON Object when a user clicks on a button. However, I have encountered an issue where my JavaScript code only saves th ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Unexpected behavior with VueJS Select2 directive not triggering @change event

Recently, I implemented the Select2 directive for VueJS 1.0.15 by following the example provided on their official page. However, I am facing an issue where I am unable to capture the @change event. Here is the HTML code snippet: <select v-select="ite ...

Optimal method to refresh v-for when updating route in Vue.js seamlessly without having to manually reload the page

What is the best approach to re-render a v-for loop in my Vue.js application when switching to another route? In my scenario, I am using Vuex, vuex-persistedstate, and moment for saving data in localStorage and displaying timestamps like "a moment ago". ...

Determine the daily volume of emails sent from the "no-reply email" address using the Nodemailer library

Our company currently utilizes Nodemailer for internal email communication. Lately, we have been encountering issues with exceeding our daily SMTP relays, resulting in some emails failing to send. To investigate further, I have been tasked with monitoring ...