防止在数组中添加重复值

Posted

技术标签:

【中文标题】防止在数组中添加重复值【英文标题】:Prevent adding duplicate values in array 【发布时间】:2021-09-23 01:00:13 【问题描述】:

我正在运行此代码并调用 ajax 请求 20 次。如果数组中还没有相同的记录,我想将 ajax 响应添加到数组中。我正在这样做,但它也在添加重复数据。我在这方面做错了什么? 我也尝试使用 indexOf 但这似乎也不起作用

有什么方法可以在每次循环运行时跳过具有相同 id 的对象?

例如,如果我收到 CID 28 的 api 响应,如果 CID 28 再次出现,我会跳过该对象添加到数组中。

for(let i = 0; i< 20; i++)
                $.ajax(
                    url: "/bin/adp/rest_api_response.megtile.json",
                    method: "POST",
                    "data":  "session": sessionID, "WIN_NBR": win, "local_time": localT.toString(), "network": "on" ,
                    beforeSend: function (xhr) 

                    ,
                    success: function (data) 

                        urls = data.btn_link;
                        var tmp_thumbnail = "url('" + data.image + "')"
                        thumbnails = tmp_thumbnail;
                        descriptions = data.banner_text;
                        btn_txt = data.btn_text;
                        titles = data.banner_title;
                        cid = data.CID;

                        console.log("datttt",arr)
                        console.log("dddd",data)
                        if (arr.includes(data) === false) 
                            arr.push(data);                        
                        
                        
                    
                );
            

API Response

    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"


Duplicate API response


    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"


API another response

    "CID": "CID3",
    "btn_link": "https://get.com/automatic",
    "btn_text": "Learn more",
    "campaign_title": "Even App",
    "banner_text": "",
    "banner_title": "Get automatic access to your earned wages every week",
    "image": "/content/uswire/en_us/me/campaigns/even-app/jcr:content/par/hero_v2_copy_cpy.g.jpeg",
    "link": "",
    "request_ID": "ae5e5396-0317-4ec8-b7b1-9f0deef5cd"

【问题讨论】:

您是否尝试过将data 转换为字符串,然后将其推送到数组中?将传入的data对象转换成字符串,然后使用arr.includes函数检查传入的data是否存在于arr中。 @decpk 不是一样的吗? @TheKNVB 是的,我试过了,它也有用 【参考方案1】:

这是一个例子来证明我所说的:

let a=
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
;
let b=
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
;
let arr=[JSON.stringify(a)];
let arr1=[a];
console.log("using the stringify method:"+arr.includes(JSON.stringify(b)));
console.log("without using the stringify method:"+arr1.includes(b));

【讨论】:

所以我在每次迭代中都这样做,对我不起作用 let x = JSON.stringify(data) console.log("xx",x) if (!arr.includes(x)) arr.push(x); 你能把重复的data对象的内容贴出来吗? 相同------------"CID": "CID28", "btn_link": "one.xyz.com", "btn_text": "访问页面", " Campaign_title”:“RFL Talkspace”,“banner_text”:“与有执照的专业治疗师交谈。”,“banner_title”:“谈论它会有所帮助。”,“image”:“/content/dam/us-wire- wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png", "link": "", "request_ID": "fa9a925b-f882-410-558-761e179eb227"【参考方案2】:

由于您尝试在对象数组中搜索对象,因此请使用自定义函数进行对象比较。下面添加我的实现方式。

const responseObj = 
  "CID": "CID28",
  "btn_link": "https://one.xyz.com",
  "btn_text": "Visit page",
  "campaign_title": "RFL Talkspace",
  "banner_text": "Talk to a licensed, professional therapist. ",
  "banner_title": "Talking about it can help.",
  "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
  "link": "",
  "request_ID": "fa9a925b-f882-410-558-761e179eb227"
;
const responseArr = [];
responseArr.push(responseObj);
const responseObjNew =  ...responseObj ;

// Using Includes method
console.log('Using array.includes', responseArr.includes(responseObjNew));

// Using Custom defined function
console.log('Using custom functon', containsObject(responseObjNew, responseArr));

// Updating Object
responseObjNew.CID = "CID13";

// Checking with updated object
console.log('Using custom functon', containsObject(responseObjNew, responseArr));

function containsObject(obj, list) 
  var isFound;
  for (let index = 0; index < list.length; index++) 
    isFound = compareObjects(obj, list[index]);
    if(isFound) 
      // Matching Object Found: EXIT
      index = list.length;
    
  
  return isFound;

function compareObjects(obj1, obj2) 
  var isMatch = Object.keys(obj1).length === Object.keys(obj2).length;
    if (isMatch) 
      Object.keys(obj1).forEach((key) => 
        isMatch = isMatch && obj1[key] === obj2[key]
      )
    
    return isMatch

【讨论】:

【参考方案3】:

如果,正如您自己已经提到的,“相同”的响应可以通过具有相同的 id 来识别,那么您可以通过使用对象而不是数组来保存从 AJAX 调用接收到的数据来简化比较:

// somewhere at the top:
var obj=; // global variable

// then, within your AJAX-related code:
// ...
cid = data.CID

if (!obj[cid]) obj[cid]=data;

如果您想以数组的形式访问结果,您可以随时从obj 中提取它

arr = Object.values(obj);

【讨论】:

【参考方案4】:

为什么不在数组创建后直接处理它?

  const people = [
      id: 1, firstName: "John", secondName: "Smith"
      id: 7, firstName: "Jack", secondName: "Foster",
      id: 7, firstName: "Jack", secondName: "Foster",
      id: 7, firstName: "Jack", secondName: "Foster"
];

那就用helprjs为你解决问题吧。

removeDuplicates(people, "id");
// [ id: 1, firstName: "John", secondName: "Smith"]

在这里试试demo

【讨论】:

以上是关于防止在数组中添加重复值的主要内容,如果未能解决你的问题,请参考以下文章

防止在字典c#中作为值添加的对象的重复变量

如何防止数组中的重复项?

如何防止 Jquery 可排序连接列表中的重复条目?

如何防止重复记录并只更新它?

如何防止用户重复提交数据

防止数组中的双重条目[重复]