How to eliminate or avoid duplicate entries in an array using Angular 2

Within my component, I have set up a subscription to a subject that is returning employee records and storing them in an array.

importResults: ImportResults[] = [];

constructor(
    private _massEmpService: MassEmpService
) {
}

ngOnInit() {
    // Subscribing to the subject for added employees data
    this._massEmpService.importedData.subscribe(obj => {
        if (obj) {
            // Keeping imported data results unique
            this.importResults.push(_.uniqBy(obj, 'QID'));
        }
    });
}

The problem I am facing is that every time the button is clicked and new data is received through this subscription, it appends the new data to the existing array instead of adding only the new records that are not already present.

Here's an example with a single record received (entering one user name and clicking search)

https://i.sstatic.net/hK8bX.png

And here's an example where I add one more user while keeping the previous one in the search field.

https://i.sstatic.net/8Jhef.png

As seen, the first array represents the original search result. The second array contains both the initial employee and the new one.

My desired outcome is to have a single array with unique objects. In this case, there should be two records since the first employee was searched twice, meaning they shouldn't be duplicated in the array as the object already exists.

Could it be that I am using the lodash function incorrectly? Also, note that QID serves as a unique identifier within the object (not shown).

Answer №1

If you want to simplify your code, consider using RxJS' distinct operator instead of manually checking for uniqueness:

this._massEmpService.data
   .filter(item => item)
   .distinct(source => source.ID)
   .subscribe(item => this.uniqueItems.push(item));

Answer №2

Discover the first object you need and push it if not found, then add it. For instance:

importResults: ImportResults[] = [];
import * as _ from 'lodash';
constructor(
    private _massEmpService: MassEmpService
) {
}

ngOnInit() {
    // Subscribe to our subject that informs us about newly added employees
    this._massEmpService.importedData.subscribe(obj => {
        if (obj) {
            // Ensure uniqueness in imported data results
            const keyExists= this._find((obj);
                if(keyExists){
                   this.importResults.push(obj);
                }
        }
    });
   }

Create a find function within the component

  private _find(cur_obj: any): any{
                return _.find(this.importResults, function (importResult: any): boolean {
                   return importResult.QID === cur_obj.QID;
                });
 }

This is just an example. Customize it according to your own objects.

Answer №3

One efficient method to eliminate duplicate items from an array involves targeting items with the same name:

var myArray= [ { 'name': 'Mac'}, {'name': 'Mac'}, {'name': 'John'} ,{'name': 'Edward'}];

console.log('----------------Before removing-------------');
console.log(myArray);
 myArray.forEach((item, index) => {
            if (index !== myArray.findIndex(i => i.name === item.name)) {
                myArray.splice(index, 1);
            }
            
        });
console.log('---------------After removing------------------');
console.log(myArray);

Answer №4

To ensure fresh data, reset the variable importResults each time the subscription is executed. Update the {} within the subscription() function with the following code:

{
  if (obj) {
    this.importResults = [];
    // Keeping only unique results in imported data
    this.importResults.push(_.uniqBy(obj, 'QID'));
  }

Answer №5

This particular code snippet doesn't cover all scenarios involving object properties. I experimented by adding more properties to the array, but unfortunately, it didn't successfully eliminate duplicates.

var myArray= [ { 'name': 'Mac', 'id': '1', 'group_id': 66}, 
{'name': 'Mac', 'id': '2',  'group_id': 55},
{'name': 'John', 'id': '3',  'group_id': 66} ,
{'name': 'Edward', 'id': '4',  'group_id': 55}, 
{'name': 'Edward', 'id': '5',  'group_id': 70}];

console.log('----------------Before removing-------------');
console.log(myArray); myArray.forEach((item, index) => {
            if (index !== myArray.findIndex(i => i.group_id === item.group_id)) {
                myArray.splice(index+1, 1);
            }

        });
 console.log('---------------After removing------------------');
 console.log(myArray);

I then attempted a different approach with this piece of code which actually proved effective:

const data = [{name: 'AAA'}, {name: 'AAA'}, {name: 'BBB'}, {name: 'AAA'}];
function removeDuplicity(datas){
    return datas.filter((item, index,arr)=>{
    const c = arr.map(item=> item.name);
    return  index === c.indexOf(item.name)
  })`enter code here`
}

console.log(removeDuplicity(data))

Answer №6

Below is a snippet of code that has proven effective for me.

The first example checks if an array contains duplicate objects:

let hasDuplicate = false;
this.items.forEach((el) => {
            if (this.items.filter(x => x === el).length > 1) {
                this.hasDuplicate = true;
                return;
            }
        });

Next, the second example demonstrates how to extract unique objects from an array:

let uniqueArr = [];
this.items.forEach((el) => {
            if (this.items.filter(x => x === el).length === 1) {
                this.uniqueArr.push(el);
            }
        });

This code snippet may be beneficial for others facing similar challenges.

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

Including a hyperlink in a table using Angular 8

I have a table with multiple columns, one of which is the "documents" column that contains downloadable files. How can I make just the document name clickable as a link? HTML <p-table #dt3 [columns]="colsPermessi" [value]="permessi" [paginator]="true" ...

The instantiation of generic types in Typescript

I have been working on a function that aims to create an instance of a specified type with nested properties, if applicable. This is the approach I have come up with so far. export function InitializeDefaultModelObject<T extends object> (): T { ...

The parameter cannot be assigned to type 'void' because it is of type 'Promise<unknown>'.ts(2345) - mockReturnValueOnce

Encountering an error while using the mockReturnValueOnce method, specifically 'Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345)'. I attempted to solve it by writing the following code: .spyO ...

The base component is not updating the property from the inherited component

Working on an Angular project where I have a component that inherits from a base component. @Component({ selector: "my-baseclass-component", template: ` <div style="border:1px solid red;padding:10px"> Counter Value (Check Co ...

Showing numeric values with decimals in an Angular Handsontable table

I want to display a decimal value (22.45) without rounding while using angular-handsontable in my application. Even though I specified the format, the value is not displayed as expected columns: ({ type: string; numericFormat: { pattern: string; }; } | {} ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...

Lazy loading routes in Angular 2 that include auxiliary router outlets

I'm currently facing an obstacle with my routing setup and could use some assistance. Previously, all my routes were organized in a single app.routing.ts file. However, I am now restructuring my routes into separate files to be lazily loaded along wit ...

Cyber Platform

I recently encountered a challenge while working on my web project. What are some areas that can be improved? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map} from 'rxjs/op ...

Explore an array to find out the frequency of each object's usage

Within our system, we have two arrays: AnswersList[], which contains all potential answers for questions. We then further divided AnswersList[] into six separate arrays: gender, age, disability, ethnic origin, religion, and sexual orientation. For this spe ...

Styling and theming in PrimeNG

Seeking advice on how to customize the appearance of the background for the primeNG panel component. I attempted to override the styling using the specific names in my scss file for the component, but it did not work. I also tried inline with <p-panel ...

Formatting the Return Values of Ionic Select

Having an issue with Ionic 3. Using an <ion-select> element with ngModel="x". When attempting to display the value in the console, it shows with extra spaces and line breaks. I tried replacing line breaks with 'e' and spaces with 'a&ap ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

Angular 2 Mastering the Art of Saving State in Routing with Precision

I have been working on a search page that retains users' search criteria even after navigating away from the page. I came across a helpful resource at that enabled me to achieve this functionality successfully. However, I encountered an issue where ...

Getting a specific element of the "Event" object using javascript/typescript

Overview I successfully integrated a select box into my Vue.js/Nuxt.js application using Vuetify.js. I utilized the @change event to capture the selected value. <v-select v-model="selectedStartTime" :items="startTime" item ...

How can I specify the type of a property in Typescript?

Looking for a solution: type WithRequiredProperty<Type, Key extends keyof Type> = Omit<Type, Key> & { [Property in Key]-?: Type[Property]; }; export type MessageWithMdEnforced = WithRequiredProperty<IMessage, 'md'>; ex ...

Resetting Tabs in Child Component using React

Imagine having two intricate React components developed in TypeScript where one acts as a child component of the other. This child component consists of tabs and keeps track of its own state to determine which tab is currently selected: export const Clien ...

Transferring the storage value to an Ionic 2 object

Extracting information from storage in Ionic 2. this.storage.get('name').then((nama) => { this.name = nama }); Now, I am trying to assign the extracted data "this.name" to an object. However, upon running the app, ...

Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads: ERROR: Property '_moveDeltaX' is protected and only accesible through an instance of class 'Container' INFO: (me ...

Combining Closure Compiler with Typescript

My objective is to leverage Typescript along with Closure Compile (advanced compilation) to target ES5 and then minify the resulting output. Is it mandatory for me to replace tsc with tsickle? I find that tsickle does not provide support for all options a ...