What are some strategies for improving search efficiency in arrays containing over 50,000 elements?

I am working with a large array of strings containing about 50,000 elements.

export const companies = [
  "000014",
  "000016",
  "000017",
  "000019",
  "000020",
  "000021",
  "000023",
  "000025",
  ...
]

These strings represent company names for which specific pages are displayed. I have implemented a middleware function that iterates through this array using a loop.

import { NextResponse, type NextRequest } from "next/server";
import { companies } from "./assets/companies";

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;

  // Loop to compare current URL path with company names
  await for (let i = 0; i < companies.length; i++) {
    if (pathname.startsWith(`/${companies[i]}`))
        return NextResponse.redirect(new URL("/", req.url)); // Redirect to main page if company name matches current path
  }
}

This process takes some time and I'm exploring ways to optimize it. One idea was to divide the array into chunks, but that may not be the most efficient solution.

Answer №1

If the pathname follows a format like /000014/abc/xyz, you can eliminate the need for array iteration by using the following approach:

import { NextResponse, type NextRequest } from "next/server";
import { companies } from "./assets/companies";

const companiesSet = new Set(companies);

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  
  // It would be better to retrieve this value from req.params.companyId, but its existence depends on the routing code, which is not visible here.
  const companyId = req.pathname.match(/\/([0-9]+)\//)?.[1];

  if (companiesSet.has(companyId)) {
    return NextResponse.redirect(new URL("/", req.url)); // redirect to main page if companies match with current pathname
  }
}

In any case, having 50,000 elements isn't considered too large and the code should not have been slow. The unnecessary await and string building within the loop could have contributed to any performance issues.

Answer №2

If you find yourself unable to rely solely on map or object lookups, such as @Aurast suggested (for instance, if you require free text searching for finding the closest matching name), then one straightforward solution is to group companies in order to break down the list into smaller segments and search within a single segment at a time. One way to do this is by dividing the companies based on their initial letter:

export const companies = {
    "a": ["aardvarks, inc", "AppendeciteCorp", ],
    "b": ["boulevard bricklayers", "bandits and bakers", "brompton fan club"],
}

By organizing the data in this manner, you can search by the first letter alone, significantly reducing the size of the array that needs to be processed. This approach is simple to implement.


Another option is to extend this concept further by recursively grouping companies based on their first letter in a data structure known as a trie or prefix tree. With this method, you can quickly search for information even when an exact match is not required.

https://i.sstatic.net/3pByO.png

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

What is the most effective method for displaying two external web pages next to each other?

Looking for a solution to display an English Wikipedia article on the left side of the page alongside its Spanish version on the right side. Wondering if it's possible using HTML, JavaScript, AJAX, etc. I am aware that I could use iframes, but I woul ...

"Apple TV now features an iOS app that allows users to watch YouTube videos

I am interested in developing an iOS application that can play YouTube videos in a UIWebView window. Users should have the option to play the videos directly on their iOS device or stream them via AirPlay to an AppleTV. The content displayed in the UIWebV ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

I recently created a "dist" folder through Babel. Is it possible to integrate the files within this folder directly into a fresh React project?

I have a React library that is available on npm. My process for publishing it involves the following steps: To begin, I create a folder called dist using Babel by executing this command- babel ./src -d ./dist Next, I upload the resulting dist directory ...

Is Sass only compatible with Ubuntu for monitoring once?

After successfully installing Sass on Ubuntu, I ran the command sass --watch scss:css and it worked perfectly. However, now I have to manually run this command every time I make changes to my code. It seems like it only works once. Can someone please ass ...

The correlation between frames per second (FPS) and the milliseconds required to render a frame in the stats plugin is known as the frame

Recently, I've implemented the Stats.js plugin to keep track of my three.js performance. Something seems off with the FPS (frames rendered per second) and MS (milliseconds needed to render a frame) information: According to my calculations, if it ta ...

What is the best way to determine the number of subchildren within a parent div using JavaScript or jQuery?

Can anyone assist me with counting the number of child divs inside a parent div using JavaScript or jQuery? I'm not very experienced in these languages. Below is my code snippet: $(function () { var parent = document.getElementById('parent& ...

Launching a centered pop-up window to display a submitted form message

I am attempting to create a page that displays a confirmation message in a center-aligned pop-up window after the user submits a form. I have managed to open the page in a pop-up window, but I am struggling to center the window using my current code (I pre ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

What will be the quickest and most reliable trigger - matchMedia, window.resize, orientationchange, or perhaps both combined?

I am trying to trigger a function when a user rotates their device and I'm seeking advice on which event would be most effective for this purpose. In your experience, which event do you recommend that will call the function quickly and consistently? I ...

Non-negotiable, non-deletable component of a text field

My goal is to create a textarea with a default value that cannot be removed by the user, but they should be able to add extra text after it. <textarea>This is constant</textarea> As shown above, the textarea has a default value. How can I ...

Confusion with Javascript callbacks - seeking clarity

I am having difficulty grasping the concept of callback functions. I know that they are functions passed as parameters to other functions. My assumption was that when a function is passed as a parameter, it would be recognized as a callback function and ex ...

Converting data from a JSON-like file format into valid JSON using JavaScript

I have a unique situation where I am dealing with numerous files that have an unusual file extension. My goal is to utilize JavaScript to read these files and then convert their contents into either JSON or regular JavaScript objects. Is this task even fe ...

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

What could be causing the show button to change its style every time I click it?

I'm a beginner in the world of JavaScript. I have been working on customizing the "show more" button and encountered an issue. I managed to add text and a down arrow below the button, but when I click it, another button labeled "I don't know how ...

The extjs datecolumn is displaying dates with a one-day discrepancy

My Ext.grid has a datecolumn, but I'm experiencing an issue where the dates displayed are off by one day. The problem seems to be related to timezones, as when data is added to the store it shows up differently later on. For example, 2013-03-31 becom ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...