Filter an array using an algorithm inspired by Binary Search Trees

I am facing a challenge with a sorted array of dates, here is an example:

let arr = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', ..]

The arr has a length of 100,000, and I need to filter this array using a binary search tree for performance reasons. However, I am unsure how to do this since a binary search tree typically returns an exact value, but I need to return all values that contain "2018", for instance.
Any suggestions on how I can achieve this?

Answer №1

To find the last occurrence of an element in a sorted array, you can utilize the upperBound method.

The Upper Bound function will return the index of the last occurrence of the specified element within the array.

const upperBound = (sortedArray, target) => {
  let start = 0;
  let end = sortedArray.length - 1;

  let rightMostIndex = -1;

  while (start <= end) {
    const mid = Math.floor((end - start) / 2) + start;
    
    if (sortedArray[mid] === target) {
      rightMostIndex = Math.max(rightMostIndex, mid);
    }

    if (sortedArray[mid] >= target) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }

  return rightMostIndex;
};

For finding the leftmost occurrence of an element in a sorted array, you can apply the lowerBound approach:

const lowerBound = (sortedArray, target) => {
  let start = 0;
  let end = sortedArray.length - 1;

  while (start <= end) {
    const mid = Math.floor((end - start) / 2) + start;
    
    if (sortedArray[mid] > target) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }

  return start;
};

Answer №2

Utilizing a binary search algorithm is an efficient way to retrieve a specific value from a dataset. In this scenario, you can repeatedly employ the method of splicing on the results obtained through the binary search process until all instances of 2018 have been removed.

The splice() function facilitates the addition or removal of items within an array while also providing the extracted item(s).

It is essential to retain the filtered values during this operation.

let data = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', '2018-01-24'];

    data.sort();
    let updatedData = [];
    let resultIndex = 0;
    while (resultIndex !== -1) {
       resultIndex = executeBinarySearch(data, '2018');
       if (resultIndex !== -1) {
          updatedData.push(data[resultIndex]);
          data.splice(resultIndex, 1);
       }
    }
    
    console.log(updatedData)

    function executeBinarySearch(data, key) { 
        let start=0, end=data.length-1; 
        while (start <= end){
            let mid = Math.floor((start + end) / 2);
            
            if (data[mid].substring(0,4) === (key)) return mid; 
            else if (data[mid] < key)
                 start = mid + 1; 
            else
                 end = mid - 1;
        } 
        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

AngularJS allows users to easily select and copy all text from both div and span elements within a specified range. This feature makes it

I am working on implementing a select all feature using AngularJS for text displayed in a structure similar to the one below. Once all the text is selected, users should be able to press ctrl + c to copy it. <div ="container"> <div class="header ...

Utilizing AngularJS to filter prices within a specific range using a button

I am new to using angularjs and I am working on implementing a price range filter with nouislider for a list of products with different prices. I want the filtering to happen only after the user clicks on the filter button. Below is the HTML code for my " ...

What is the process for altering a variable within an Ajax function?

Scenario: I'm dealing with JSON data fetched from the backend which needs to be presented in a table format. To achieve this, I've created a string called tableOutputString and am populating it by iterating through the JSON response. Finally, I&a ...

Locate relevant information within the arrays through the process of filtering

For my collection, I am looking to match the operator_name based on date and then further narrow it down by matching shift_name within an array { "_id": "5eb301bc0218ff48b724a486", "date": "2020-07-02T00:00:00.000Z", "shift_wise": [{ "_id": ...

After the update, Material UI is causing a TypeError by throwing an error stating that it cannot read the property 'muiName' of an

After updating from "material-ui": "^1.0.0-beta.38" to "@material-ui/core": "^1.3.0", I made changes to imports, ran npm install, removed node_modules and even deleted package-lock.json. However, I continue to encounter the cryptic error message TypeError: ...

What is the best way to utilize AJAX to upload several images in PHP?

I have a UI that looks like this: https://i.sstatic.net/BAbwP.jpg I am trying to upload multiple videos using ajax in PHP. I attempted to use FormData() in jQuery for this purpose. However, it seems to only upload one image and not more than that. Her ...

Using Javascript outside of the AngularJS environment

I am trying to utilize Javascript functions outside the controller in Angular JS instead of using a service within a module. Is this allowed? For instance: var UrlPath="http://www.w3schools.com//angular//customers.php" //this section will store all the f ...

Testing the functionality of an Express Rest API with Mocha unit tests

I have just started diving into the world of unit testing. While I've been successful in running simple tests such as "adding two numbers and checking if the result is greater than 0", my goal now is to develop a REST API using Test-Driven Development ...

Using React Native to integrate a JSON string into a button

I'm currently working on an app to explore the functionality of websockets in react native. I have successfully retrieved data from the websocket in JSON format and can output it to the console using console.log. However, my goal is to display a speci ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

Execute an HTTP POST request to the Node server, sending an empty object

For my project, I am attempting to send an HTTP Post request to my Node server from an html form. Despite using Body Parser and setting it up correctly, I am facing an issue where the req.body on my server is returning as an empty object. Can anyone prov ...

Error found in event.PreventDefault()

I'm currently implementing Twitter Bootstrap on my application. I added e.preventDefault for the link button within $(document).ready(), but it doesn't seem to be functioning properly. Below is the code snippet: Master page: <a id="lnkLogou ...

Is there a way to alter the text color using JavaScript on the client side?

Is there a way to change the color of a list item in a ul based on whether it is a palindrome or not? Here is the JavaScript file I am working with: function isPalindrome(text){ return text == text.split('').reverse().join(''); } c ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

Can anyone suggest methods for displaying query data from a JSON file using HTML?

After countless hours of searching through various forums, I have attempted numerous methods to display query data from a JSON file onto an HTML page. My initial attempt was using XmlHttpRequest, which yielded no results. I then tried utilizing jQuery, sp ...