typescript Angular2 删除/防止数组中的重复记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45090629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:42:57  来源:igfitidea点击:

Angular2 remove / prevent duplicate records in array

angulartypescriptlodash

提问by SBB

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

我有一个订阅 a 的组件,subject它返回员工记录并将它们放入一个数组中。

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.

我在这里的预期结果是有一个具有唯一对象的数组。这意味着我的示例中应该有 2 条记录,因为第一个员工被搜索了两次,他不应该被推送或包含到数组中,因为该对象已经存在。

Am i using this lodashfunction incorrectly? QIDis a unique valid key in the object as well (not pictured).

我是否lodash错误地使用了此功能?QID也是对象中唯一的有效键(未显示)。

回答by Shailesh Ladumor

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

如果没有找到,你可以找到第一个 uoy 对象,无论你想推什么,然后推它。例如

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

这是例子。你可以根据你的对象改变它

回答by Gruff Bunny

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

您可以使用 RxJS 的不同操作符尝试这样的操作,而不是自己手动检查唯一性:

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

回答by suriya prakash

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

回答by Hardeep

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

回答by Rajeev Kumar

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.

我希望它会帮助某人。

回答by Praveen Premaratne

You can reset the importResultsvariable every time the subscriptionruns. Just replace the {}in the subscription()with this:

您可以在importResults每次subscription运行时重置变量。只需将{}中的替换为subscription()

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