Exploring the presence of duplicates in JavaScript and/or AngularJS

While working on my AngularJS app, I found myself iterating through a .csv file to perform element level validation. Since I couldn't find a suitable library in Angular, I decided to write custom JavaScript code to handle this scenario. Below is a sample of the data I'm working with (specifically interested in the first column CN and the 5th column NAME). My approach so far involves using if conditions to check the index of i, j, and store the values. Any suggestions or improvements would be greatly appreciated.

CN  N   ACTIVE  TYPE    NAME       NO   COM
USA 45  Engin   Fed     Anderson   #10  NA
USA 46  Sports  BB      Kobe       #1   NA
USA 32  Sports  Soccer  Kobe       #17  NA
GER 30  Sports  Soccer  Gotze      #12  NA
GER 27  Sports  Soccer  Ozil       #18  NA
ITA 38  Sports  Soccer  Buffon     #2   NA

Here's a snippet of the code:

for (var i = 0; i < file.length; i++ ){
    var singleRowData = file[i].split(',');
    singleRowData = singleRowData.filter(function(n){ return n != "" });
    for (var j = 0; j < singleRowData.length; j++){
        duplicateFunction(singleRowData, singleRowData[j], j, i);
    } 
}  

function duplicateFunction (singleRowData, singleRowDataElement, singleRowDataElementIndex,  singleRowDataIndex){
/*
  handle the duplicates
*/
}
  1. If I come across the same values in the CN column for consecutive rows, then I want to check if there are duplicate values in the NAME column for those rows.
  2. If there are no duplicate NAME values for different rows with the same CN value, then no error should be thrown.

In the example data provided, an exception should be flagged on the 3rd row where CN=USA and NAME=Kobe, while the rest of the data should proceed without issues.

Answer №1

To easily identify duplicates, you can concatenate the key pairs (CN + NAME) and store them in a keys object. If a new record contains the same concatenated key, it means there is a duplicate:

var file = [
    'USA,45,Engin,Fed,Anderson,#10,NA',
    'USA,46,Sports,BB,Kobe,#1,NA',
    'USA,32,Sports,Soccer,Kobe,#17,NA',
    'GER,30,Sports,Soccer,Gotze,#12,NA',
    'GER,27,Sports,Soccer,Ozil,#18,NA',
    'ITA,38,Sports,Soccer,Buffon,#2,NA'
];

var keys = {}; // store processed keys
var result = []; // array with accepted rows
for ( var i=0; i< file.length; i++ ){
    var singleRowData = file[i].split(',');
    singleRowData = singleRowData.filter(function(n){ return n != "" });
    var key = singleRowData[0] + '|' + singleRowData[4]; // CN + NAME
    if (key in keys) {
        console.log("Duplicate at " + i + " is ignored");
    } else {
        keys[key] = 1; // register key
        result.push(singleRowData);
    }        
}  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For a more concise ES6 approach using an ES6 Map and reduce, consider the following implementation:

const file = [
    'USA,45,Engin,Fed,Anderson,#10,NA',
    'USA,46,Sports,BB,Kobe,#1,NA',
    'USA,32,Sports,Soccer,Kobe,#17,NA',
    'GER,30,Sports,Soccer,Gotze,#12,NA',
    'GER,27,Sports,Soccer,Ozil,#18,NA',
    'ITA,38,Sports,Soccer,Buffon,#2,NA'
];

const result = [...file.reduce( (result, line) => {
    const singleRowData = line.split(',').filter(n => n != ""),
          key = singleRowData[0] + '|' + singleRowData[4]; // CN + NAME
    return result.has(key) ? result : result.set(key, singleRowData);
}, new Map).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

When making a $http request in Angular, the passport req.isAuthenticated method consistently returns false

I have implemented user authentication in my application using passportjs. When testing with postman, the login process is successful and req.isAuthenticated always returns true in subsequent requests after logging in. However, when using angular $http f ...

Encountering a glitch while utilizing BreezeJS alongside AngularJS

Encountering errors while using BreezeJS with AngularJS. One common issue is receiving a "running out of stack space" error in the console when utilizing the 'filter' function within an ng-repeat loop. Here are the steps to replicate the problem ...

How can I retrieve the selected items from a Listbox control?

Currently, I am working on an ASP.NET application using C#. One of the features in my project involves a Grid View with a Listbox control. The Listbox is initially set to be disabled by default. My goal is to enable and disable this control dynamically bas ...

JavaScript Drag Events in Microsoft Edge (Including IE)

My drag event is functioning properly in Chrome, Safari, Firefox, and Opera. However, I encountered an error when running it on Microsoft Edge and IE: SCRIPT438: Object doesn't support property or method 'setDragImage' Below is the code sn ...

Using regular expressions to replace all special characters, excluding dots

$('#price').keyup(function(){ $('#price').val($('#price').val().replace(/[_\W]+/g, "-")); }) Experience it firsthand here: http://jsfiddle.net/2KRHh/6/. In the scenario above, special characters are eliminated. ...

Invoke a function within a distinct context using a loop

I'm currently using a script where a function is called for each element on the page. It works fine when I make separate function calls, but if I try to call the function with a unique selector, it doesn't work as expected. Is there a way I can c ...

Encountered a JavaScriptException while trying to click on an element using Selenium and Python: "arguments[0].click is not a function"

When practicing web scraping, I have been extracting locations from various websites. This particular code helps me pinpoint individual city locations of a hotel brand. However, every time I use driver.execute_script("arguments[0].click();", button) in my ...

Deactivate a form on the page while another form is being used

My issue involves having two forms on the same web page with identical IDs, and I'm unable to easily change them. Both forms are necessary on the page. When I submit one form, it also submits the other form as blank, resulting in duplicate submission ...

Maximizing search engine optimization for an AngularJS website

What is the best approach for implementing search engine optimization (SEO) on a website created using AngularJS? Kindly provide an explanation of the methods and techniques that can be used. ...

What is the best way to modify the state of a particular element in an array when using useState in React?

In my Next.js application, I am using a useState hook to manage state. Here is how my initial state looks like: const [sampleData, setSampleData] = useState({ value1: '', value2: '', value3: [] }); To update the state ...

Uploading a large number of images to GCP Bucket results in a failure to connect to the oauth2 token

After writing a NodeJS upload function for Google Cloud bucket, I encountered an issue when trying to upload a larger dataset of over 3000 images. Initially, the uploading process seemed smooth, but then suddenly an error occurred and only some of the imag ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

Integrate SVG directly into the three.js module to eliminate the need for an additional HTTP request

Currently, I am developing a small website that features a simple 3D animation. The model is extruded from an SVG file loaded using SVGLoader. My goal is to enhance the loading speed by including the SVG as text in my threejs code, eliminating the need for ...

Customizing Images using a JSON array of images

Looking to implement a feature that displays images fetched from a CMS via a JSON file. The JSON data structure is as follows: { "images": [ {"title": "Image One", "url": "image1.jpg"}, {"title": "Image Two", "url": "image2.jpg"}, {"title": "Ima ...

Syntax Error Unearthed: Identifier Surprise Discovered in (Javascript, ASP.NET MVC, CSHTML)

I encountered an error when attempting to remove a dynamically created HTML element by clicking the corresponding remove button. The goal is to invoke the remove method at the end of the script and pass along certain arguments. However, I'm facing iss ...

The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup: <ul> ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

What is the method for incorporating PHP's header() function within PayPal JavaScript code?

I'm currently working on integrating Paypal with my website and I've run into some issues handling the various messages sent by Paypal, such as success, failed, and cancelled transactions. Below is a snippet of the Paypal JS code where it manage ...

Step-by-step guide on repairing a countdown clock using JavaScript, HTML, and

I'm having issues with my JS on my website. I am new to this and currently in the process of setting up a website. I want to add a timer to show when the site will be active. It seems like there is an error somewhere in the JS code that I can't ...