Discovering duplicates in an array list with Angular 6 by using the 'some' method

Greetings! I am currently working with an array of values, as shown below:

    var users = [{
        name: 'John',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f9fcfbfde0fcfdd3fef2faffbdf0fcfe">[email protected]</a>',
        age: 25,
    },
    {
        name: 'Tom',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b60624f626e6663216c6062">[email protected]</a>',
        age: 35,
    },
    {
        name: 'John',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e444146405d41406e434f4742004d4143">[email protected]</a>',
        age: 25,
   }];

My task is to identify duplicate entries within this array by comparing all the fields - name, email, and age.

To address this, I have implemented a function to check for duplicate values, but now I need to incorporate multiple conditions into it. How can I achieve this?

 const unique    = new Set();

 const showError = this.users.some(element => unique.size === unique.add(element.name).size);

Since I have only checked for duplicates based on the name field, I also require validation for email and age. What approach should I take for this multi-condition verification process?

Answer №1

To determine the status, maintain a counter while comparing objects. Since every object will be equal to itself, check if the counter is greater than 1 to determine the status.

const status = users.some(user => {
  let counter  = 0;
  for (const iterator of users) {
    if (iterator.name === user.name && iterator.email === user.email && iterator.age === user.age) {
      counter += 1;
    }
  }
  return counter > 1;
});

Answer №2

var usersData = [
  {
    name: 'Alex',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9c2c8c7ccf9c6c8c0c580cdc1c3">[email protected]</a>',
    age: 28,
  },
  {
    name: 'Emma',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="356d60726162637560">[email protected]</a>',
    age: 31,
  },
  {
    name: 'Alice',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8adbb0aba4a5aab9beb4bccbc6cab8bffaca324f4341">[email protected]</a>',
    age: 34,
  },
  {
    name: 'Alex',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f59bd19197b69b93939fd3909597">[email protected]</a>',
    age: 28,
  },
  {
    name: 'Claire',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86efe5eae1c4eb e5ede8aa }," 15) "> [email protected] </A>',
    age: 30,
  },
];

// function complexity is based on the number of user data items
var newData = getUniqueData(usersData, 'email');
console.log(newData)

function getUniqueData(array, keyField) {
  var uniqueItemsArray = [];
  var itemMap = new Map();

  array.forEach((item, index) => {
    if (index === 0) {
      itemMap.set(array[index].email, array[index].email);
      uniqueItemsArray.push(array[index]);
    }
    
    if (!itemMap.get(item[keyField])) {
      itemMap.set(item[keyField], item[keyField]);
      uniqueItemsArray.push(item);
    }
  });
  
  return uniqueItemsArray;
}

Answer №3

To eliminate duplicate entries, utilize the following code snippet:

const removeDuplicates = (array, key) => {
    let lookup = {};
    return array.filter(obj => !lookup[obj[key]] && lookup[obj[key]] = true);
}

Answer №4

Give this a shot:

Let's attempt this solution:
const flagError: boolean = Array.from(new Set(players.map(player => JSON.stringify(player)))).length != players.length;

Answer №5

let countOccurrences = users.reduce(function(counts, item) {
    if (item in counts) {
        counts[item] += 1;
    } else {
        counts[item] = 1;
    }
    return counts;
}, {});

let resultList = [];

for (let key in countOccurrences) {
    if (countOccurrences[key] > 1) {
        resultList.push(key.split(",").map(function(item) {
            return parseInt(item);
        }));
    }
}

console.log(resultList);

I trust this solution will be of assistance.

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 the width of a div element in Angular 2

I have encountered several posts, but none of them quite achieve what I am trying to do. I am dealing with a table that exceeds the width of the page and, due to certain requirements, I need to measure its width. I attempted: @ViewChild('tableToMea ...

The 'HTMLDialogElement' cannot be located by @types/react

I have encountered a strange issue while building my typescript project with @types/react. I have separate typescript configuration files for react and non-react files. However, when I try to build the portion of my project that doesn't use react, I a ...

Invoke a different route within Express Router when it needs to display a Not Found error (404)

Hey there, how are you? Below is the code I've been working on: const router = Router(); router.use( `${routePrefix}/v1/associate-auth/`, associateAuthRoutesV1(router) ); router.use( `${routePrefix}/v1/associate/`, JWTVerify, ...

Strategies for extracting methods and refactoring to a separate file for better reusability

Still relatively new to the JQuery/javascript realm, I've put together a functional jqgrid with a datepicker and custom control (using jquery auto complete) by piecing together code samples I came across online. This code has been added to a T4 templa ...

Deactivate specific choices from a dynamically generated dropdown menu in Angular 8

I am working on a dynamic dropdown feature with multiple fields. https://i.sstatic.net/28iQJ.png By pressing the + button, a new row is generated. Users can add any number of rows. My challenge is to prevent users from selecting previously chosen values i ...

Angular 2 throwing error message: "Undefined function found"

Having trouble with a grid setup like this: this.columns= [ { text: 'S.No', columntype: 'textbox', filtertype: 'input', datafield: 'id', width: 50, cellsalign: 'center' }, { t ...

What is the best way to modify the value of an external variable within a promise?

var isError = false; savedata.ingredients.split(',').reduce(function(p, ing) { return p.then(function() { return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId }); }); }, Promise.resolve()).catch(function( ...

Here is a unique way to write it: "Gain access to the data contents, loading status, and error flag by initiating the useFetch

After following this article, I successfully implemented it: Below is the useFetch code. export const useFetchData = () => { // Data; const [dataContents, setDataContents] = useState([]); // URL; const [url, setUrl] = useState('http://exam ...

Guide to utilizing Regex validation for checking the vehicle registration plate in Vue 3 input field

I need to implement validation for an input field that only accepts capital letters and numbers, following a specific format (AAA-111). The first 3 characters should be alphabets, followed by a hyphen, and then the last 3 characters should be numbers. & ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

The React application, when built using `npm run build`, experiences difficulty loading image sources after deployment to App Engine

In my React frontend application, I have the logo.png file being loaded in Header.tsx as an img element like this: <img className={classes.headerLogo} src={'logo.png'} alt={"MY_LOGO"}/> The directory structure looks lik ...

Sending colored output from stdout to grunt's output stream

Having trouble creating a custom grunt task that runs mocha tests and displays colored output? I'm running into an issue where grunt is stripping out the colors from the mocha command's output. Here's the code for the grunt task: var exec = ...

Can the variable name be customized according to the input given?

My goal is to create multiple columns with randomized results independently of each other, based on user selection. I am not sure how many columns there will be, and I want the function to be repeatable as needed. While I know how to achieve this in PHP (u ...

Reveal Particular DIVs When Certain DIVs are Concealed

Snippet - http://jsbin.com/udumibO/1/edit In the scenario where certain div elements are hidden using the .hide() event handler, I am looking to make two other divs visible instead. I attempted to achieve this on document.ready, however, the code is not ...

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

Debugging is not possible for applications running on an Android device with Ionic 2

Instructions to replicate the issue: 1. Begin by creating a new project from the following repository: https://github.com/driftyco/ionic-starter-super 2. Execute the command `ionic run android` 3. Utilize chrome://inspect for debugging purposes The ...

Encountering "Cannot find module" errors while using the most recent version of WebStorm 2019.3 with Angular

Since updating to Angular 9, I've been encountering errors in the TypeScript error console. Strangely, no errors are shown when I run 'tsc' in the command line. https://i.sstatic.net/3mNGp.png This is my tsconfig file: { "compileOnSave" ...

Converting Java ArrayLists to JList format

Currently working on updating my inventory system. I've got most of it figured out, but now I'm trying to store string items in an ArrayList and then display them in a JList. Unfortunately, I keep encountering this error during compilation: C:&b ...

Execute a function within useEffect continuously until the contract is fully loaded

When I make the call contract?.methods.name().call() within the same scope as loading providers, everything works perfectly fine. It also works fine when I do a page reload. However, if I make the call contract?.methods.name().call() in another useEffect, ...

Displaying the last time a post was updated, similar to the notification system used on

In my development work, I often utilize momentJs to calculate the time difference between now and a specific date. Here is an example of how I use it: moment([MyDate]).fromNow(); This code typically returns results such as: "a few minutes ago" or "10 ...