SBB
SBB

Reputation: 8970

Angular2 remove / prevent duplicate records in array

I have a component that is subscribed to a subject which is returning employee records and putting them into an array.

importResults: ImportResults[] = [];

constructor(
    private _massEmpService: MassEmpService
) {
}

ngOnInit() {
    // Subscribe to our subject that lets us know about the added employees
    this._massEmpService.importedData.subscribe(obj => {
        if (obj) {
            // Ensure that we have unique results in our imported data
            this.importResults.push(_.uniqBy(obj, 'QID'));
        }
    });
}

My issue is that each time my button is clicked and this subscription receives data, its pushing the new data along side what is already there instead of ONLY adding records that don't exist.

Here is an example on a single record received (I entered one user name and clicked search)

enter image description here

Here is an example when I add one additional user, leaving the previous one in the search field.

enter image description here

As you can see, the first array is the original search result. The second array contains the first employee AND the new employee.

My expected outcome here is that there is a single array with unique objects. This would mean there should be 2 records from my example since the first employee was searched two times, he shouldnt be pushed or included into the array since that object already exists.

Am i using this lodash function incorrectly? QID is a unique valid key in the object as well (not pictured).

Upvotes: 0

Views: 14676

Answers (6)

Rajeev Kumar
Rajeev Kumar

Reputation: 371

You can try below code which worked for me.

1st example to identify whether array has duplicate object or not.

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

2nd example to get unique object from array.

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

I hope it will help someone.

Upvotes: 0

Hardeep
Hardeep

Reputation: 11

This code doesn't really apply to all the object properties scenarios. I tried adding more properties to the array, and it didn't really remove the duplicacy.

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);

So I tried this code and this actually worked:

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))

Upvotes: 0

suriya prakash
suriya prakash

Reputation: 47

A simple way to remove the duplicates items in the array is by: Here I remove items that with duplicate names

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);

Upvotes: 1

Gruff Bunny
Gruff Bunny

Reputation: 27976

You could try something like this using RxJS' distinct operator instead of manually checking for uniqueness yourself:

this._massEmpService.importedData
   .filter(obj => obj)
   .distinct(src => src.QID)
   .subscribe(obj => this.importResults.push(obj));

Upvotes: 2

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7242

you can find first uoy object whatever you want push if not found then push it. for example

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

ngOnInit() {
    // Subscribe to our subject that lets us know about the added employees
    this._massEmpService.importedData.subscribe(obj => {
        if (obj) {
            // Ensure that we have unique results in our imported data
            const keyExists= this._find((obj);
                if(keyExists){
                   this.importResults.push(obj);
                }
        }
    });
   }

create find function into component

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

this is example. you can change it based on your objects

Upvotes: 2

Prav
Prav

Reputation: 2894

You can reset the importResults variable every time the subscription runs. Just replace the {} in the subscription() with this:

{
  if (obj) {
    this.importResults = [];
    // Ensure that we have unique results in our imported data
    this.importResults.push(_.uniqBy(obj, 'QID'));
  }

Upvotes: 0

Related Questions