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.

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

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...

Discover a technique to display every individual "echo" statement from PHP in sequence, rather than waiting for the entire script to finish executing

I have developed a PHP script that takes some time to execute and displays multiple "echo" statements as the progress is being made. The script connects to an FTP server, deletes all contents, and then uploads new files. Everything is functioning correctly ...

Guide on incorporating mouse movement while the mouse button is held down in JavaScript

For my project, I want to activate the mouse move event only when the mouse button is held down. I specifically need the action "OK Moved" to be triggered only when both the mouse button is held down and there is mouse movement. This is the code that I h ...

Is there a method to make this package compatible with Angular version 16?

I recently integrated the ngx-hotjar package version 11.0.0 into my Angular 10 project with success. However, when trying to use it in a new Angular 16 project, I encountered the following error during ng serve: Error: src/app/app.module.ts:275:12 - error ...

Creating a dynamic dropdown menu using JQuery that does not automatically submit the form when a value is

Upon selecting a background color from the dropdown menu, I am generating a dynamic dropdown for text colors. The Text Color dropdown is populated correctly based on the selection of Background Color. Although the functionality works as intended, I encoun ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Experience seamless integration of Mantine UI with NextJS when utilizing useMantineColorScheme. Uncover the power of color customization,

I am currently working on integrating Mantine UI library into my NextJS application, but I have encountered an issue during setup. Even though I followed the setup instructions as per the documentation, I am facing the following error: Error: useMantineC ...

Finding the offsetWidth (or similar measurement) for a list item (LI) element

Can jQuery be used to determine the width of an element? alert($("#theList li:eq(0)").offsetWidth); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="theList"> <li>The quick brown ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image. Below is the HTML & Java code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div> ...

AngularJS- issue with button visibility on 'toolbar' widget

In my angularJS application, there is a page with multiple widgets displayed. When a user clicks on the 'Settings' button on the page (separate from the widgets), a toolbar for each widget appears showing different buttons depending on the widget ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using: <html> <head> <link type="text/css" rel="stylesheet" href="html.css" /> <script type="text/javascript"> function getName() { if(name) alert("Did y ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

Incorporate javascript into your XML transformations with XSLT

I need help with inserting JavaScript in XSLT. Here is an example of what I am trying to do: <xsl:variable name="comboname" select="@name" /> <script type="text/javascript"> var z{$comboname} = {$comboname}; </scri ...

Unable to resubmit form via ajax more than once

Greetings to all, I seem to be encountering some issues with a supposedly simple form submission using ajax. Upon the initial submission of the form by the user, everything proceeds smoothly: The content within the div changes as expected and the PHP proc ...