检查angular2中对象数组中的重复值 [英] Check for duplicate values in array of objects in angular2

查看:51
本文介绍了检查angular2中对象数组中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项要求,我只需要检查对象数组中的重复描述.下面是对象示例.

I have a requirment where i need to check for only duplicate description in array of objects. Below is the object example.

traveler = [
   {  description: 'Senior', Amount: 50},
   {  description: 'Senior', Amount: 10},
   {  description: 'Adult', Amount: 75},
   {  description: 'Child', Amount: 35},
   {  description: 'Infant', Amount: 25 },
   {  description: 'Adult', Amount: 105},
];

在上面的数组行进器中,存在带有重复说明的对象,因此如何只检查整个数组中是否存在重复说明并显示一条消息.

In the above array traveler there are objects with duplicate description, so how to check only for duplicate description throught out the array and display a message.

我正在使用reduce方法,下面是代码.但是控件没有进入if循环

I am using reduce method,below is the code. but the control is not going inside the if loop

我在哪里出错了?

var res = traveler.reduce((acc, obj)=>{
         var existItem = acc.find(item => item.description === obj.description);
            if(existItem){
                return this.toaster.pop('info', 'Insertion unsuccessful', 'Duplicate answer found')
            } 
           });

推荐答案

尝试一下.

reduce(){
   let res=[];
   this.traveler.map(function(item){
     var existItem = res.find(x=>x.description==item.description);
     if(existItem)
      console.log("item already exist");
     else
      res.push(item);
   });
   console.log(res);
 }

这篇关于检查angular2中对象数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆