Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation is Angular-based.

One of the initial steps involves checking for duplicates within the array and storing them separately[...]. To achieve this, the following code snippet is used:

validateTargets(targets: string[]): ValidationResultObject[] {

    let result: ValidationResultObject[];
    let dups: string[] = [];

    var uniques = targets.filter( (item,index) => {
        if (targets.indexOf(item) === index) {
            return targets.indexOf(item) === index
        }
        else {
            dups.push(targets[index])
        }
    }

    //additional validation procedures are carried out here

    return result;
}

The main issue arises when processing an array above 50K items, causing a noticeable freeze in the UI. As a temporary fix, the aforementioned callback function has been placed within a setTimeout, allowing a spinner to indicate activity while the page hangs :)

Various suggestions exist on how to structure code to ensure UI responsiveness, but my scenario presents a challenge due to duplicate handling.

One potential solution considered was breaking down the array into chunks and processing the Array.filter method in a loop using setTimeout for UI responsiveness. However, eventually comparing these chunks against each other would only prolong the process! With some browser limitations within the organization, experimenting with workers isn't currently feasible.

If anyone has insight or suggestions on how to address this dilemma, it would be greatly appreciated. Unfortunately, migrating this functionality to the backend is not an option :(

Best Regards

Answer №1

If you want to efficiently filter out duplicate elements from an array, consider using the following code:

let uniqueItems = targets.reduce((result, item) => {
  result[item] = 1;
  return result;
}, {});
let noDuplicates = Object.keys(uniqueItems);

This method only requires one pass over the array and takes advantage of the internal efficiency of property name lookup for faster processing compared to using .indexOf() for sequential search. When dealing with arrays containing a large number of elements, this approach should significantly reduce execution time.

Answer №2

To efficiently process a large amount of data, consider implementing an asynchronous function. Once the processing is complete, use a callback to pass the result as an argument and resume normal flow.

async validateTargets(targets: string[], callback: function): {
 //...Custom logic
 callback(result)
}

If you need to eliminate duplicates, you can utilize

[...new Set(items)]

Important: The above approach assumes that the Items array only contains primitive values.

Answer №3

Although I have not encountered this scenario before, my advice would be to consider utilizing the Set type in JavaScript. This data structure automatically removes duplicates internally, making it more efficient than using filter methods. For reference, you can read more about the performance comparison between JS Set vs Array. In case there are browsers that do not support Set, you can always use a polyfill as an alternative solution.

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

Is there a way for me to immediately send data after receiving it?

When I try to perform onPress={() => kakaoLosing() I am attempting to retrieve data (profile) from getProfile using async await and immediately dispatch that data to KAKAOLOG_IN_REQUEST, This is my current code snippet: import { ...

What is the best way to bring an image into your nextjs project?

I have a question about importing images into my Next.js project. I created an array of objects and want to import an image stored in a folder on my laptop, specifically in the src folder rather than the public folder. How can I properly achieve this in ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

Is it considered best practice to include try/catch blocks within the subscribe function in RxJs?

Imagine we have an Angular 2 application. There is a service method that returns data using post(), with a catch() statement to handle any errors. In the component, we are subscribing to the Observable's data: .subscribe( ()=> { ...

Is there a way to easily uncheck all MaterialUI Toggle components with the click of a button or triggering an outside

If you have a set of <Toggle /> components in an app to filter clothes by size, and you want to reset all the filters with a single click on a button rather than unchecking each toggle individually. Is it possible to achieve this using materials-ui ...

What is the method for obtaining the input value of an input type number in HTML?

Within my form, there is a number field where users can input scores: <input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please input a score from 0-10 ...

The retrieved information remains unchanged even after modifications are made on the subsequent Next.js server-side rendered page

I'm facing an interesting scenario with my application. It consists of two main pages - one displaying user account statistics and the other allowing users to edit these statistics. Both pages are rendered on the server side. When I navigate to the fi ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

Styles are ineffective on the focus property, although they do work before the focus is applied

I'm having trouble changing the font color of the TextInput in material UI. It seems to change to white when I click away, but then reverts back to a purple-ish color (the default) when I focus on it again. I'm not sure what I'm missing here ...

Eliminate items from one array when there is a corresponding match in a separate array using JavaScript

I am working with 2 JavaScript arrays First Array var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}]; Second Array var unSel ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Trouble with RegExp functionality within prisma's aggregateRaw when using MongoDB

I'm currently learning about MongoDB and Prisma in JavaScript. The following code snippet shows a MongoDB query using Prisma's aggregateRaw method. In this case, the cond is used to perform a case-insensitive string comparison. For instance, if $ ...

Combining type inference validation and authentication middleware in Express routes can be a powerful way to enhance security and ensure

I am struggling to grasp how types are automatically determined in Express routes when utilizing multiple middlewares. To conduct validation using zod, I have employed the middleware package express-zod-safe, although a similar issue arose with alternativ ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Make a tab the active tab within the Material-UI tab component

For the current project, I have decided to utilize Material UI as the primary library. One of the pages in the project requires four tabs, which I am implementing using the tab component from the Material UI library. By default, when rendering the page wi ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...