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

finding and retrieving every occurrence of the select directive and its corresponding selected values in Angular

I recently set up a chosen dropdown in my project using the following method. I added a select box with a "chosen" directive as an attribute to update and initialize a list, along with an ng-model on the select element. <select id="{{$index+1}}" class= ...

Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI. The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node. Here is what I have attempted so far: def inputFile = new File( ...

What is the process of building a service in AngularJS?

I have written this code using a service in angular.js. Upon running the code, I encountered an error Uncaught Error: [ng:areq]. </ons-toolbar> <div ng-controller="testAppController"> Search: <input ng-model="query" type=" ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

Guide on converting the <br> tag within a string to an HTML tag in VUE.js

When working with Vue.js, I often use {{}} to display my data on the HTML page. However, I recently encountered a situation where my data includes a string with tags that I would like to be rendered as actual HTML tags when displayed. data(){ return ...

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

When using JQuery, data may not be displayed in another function even when using the same command

Hello, I'm new here and encountering a strange problem with two functions in my script. Let me show you the first function: $(document).on("click", "#result2 p", function(){ var inv_id = $(this).text(); $.get("autocomplete_inv.php", ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

The method request.getParameter in Servlet may sometimes result in a null

My website utilizes JQuery to make an Ajax call to a servlet. function sendAjax() { $.ajax({ url: "/AddOrUpdateServlet", type: 'POST', dataType: 'json', ...

Is there a way to use JQuery to dynamically generate a new select box with specific options?

I am looking to dynamically create a new select box based on the value selected in an existing select box using jQuery. Currently, the code we have implemented is not functioning correctly. <script src="http://code.jquery.com/jquery-1.5.min.js">&l ...

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

npm socket.io installation failed due to node version being less than 0.10.0

Having trouble installing socket.io on my BeagleBone Black because my system is using Node v0.8.22, but the required version for installation is above 0.10.0. Unfortunately, I am unable to upgrade my Node. /usr/bin/ntpdate -b -s -u pool.ntp.org cd /var/li ...

Ways to dynamically incorporate media queries into an HTML element

Looking to make some elements on a website more flexible with media rules. I want a toolbar to open when clicking an element, allowing me to change CSS styles for specific media rules. Initially thought about using inline style, but it turns out media rul ...

Bringing in More Blog Posts with VueJS

Exploring the Wordpress API and devising a fresh blog system. As a newbie to VueJS, I'm intrigued by how this is handled. The initial blog posts load as follows: let blogApiURL = 'https://element5.wpengine.com/wp-json/wp/v2/posts?_embed&p ...