Javascript在插入数组之前检查重复

问题描述 投票:0回答:2

在插入array之前尝试检查多个字段的副本时遇到了一些问题。我想要做的是从firebase检索,检查accountIDsubtype字段之前插入array由Promise解决。

我想要实现的是如果相同的accountID,不同的subtype,那么我补充;如果相同的accountID,同样的subtype,我移动到下一个;如果不同的accountID,不同的subtype,我补充说。这是我的代码:

码:

var datasetarr = [];
let promiseKey = new Promise((resolve, reject) => {
                for(var i = 0; i < receiptlist.length; i++){
                    for(var k = 0; k < ritemlist.length; k++){
                        if(receiptlist[i].date.substring(0, 4) == new Date().getFullYear()){
                            if(ritemlist[k].receiptID == receiptlist[i].receiptID){
                              //check duplicate here before insert
                                if (!datasetarr.find(o => o.accountID === receiptlist[i].accountID && o.subtype === ritemlist[k].type))
                                    datasetarr.push({accountID: receiptlist[i].accountID, subtype: ritemlist[k].type});
                                }
                            }
                        }
                    }
                }
            resolve(datasetarr);
            });

我尝试打印数组时的部分:

数组:

promiseKey.then((arr) => {
            console.log(arr);
});

我得到的输出:

输出:

enter image description here

我仍然看到很多重复使用相同的accountID和相同的子类型。无论如何要解决这个问题?

谢谢!

javascript arrays duplicates
2个回答
0
投票

如果没有您的数据,find会返回undefined;所以你要做的就是检查返回的值是否为undefined,然后进行计算

  var found = datasetarr.find(o => o.accountID === receiptlist[i].accountID && o.subtype === ritemlist[k].type)
     if (found === undefined){
         //do computation
     }

0
投票

您可以使用lodash这是一个非常好的数组处理库。

在你的情况下,数据应该是accountId唯一的,你的数据存储在数据变量中,你可以像这样使用_.uniqBy()函数:

jvar datasetarr = []; 
  let promiseKey = new Promise((resolve, reject) => {
            for(var i = 0; i < receiptlist.length; i++){
                for(var k = 0; k < ritemlist.length; k++){
                    if(receiptlist[i].date.substring(0, 4) == new 
                       Date().getFullYear()){
                        if(ritemlist[k].receiptID == receiptlist[i].receiptID){
                                  //Push your object here.
                                datasetarr.push({accountID: receiptlist[i].accountID, subtype: ritemlist[k].type});
                            }
                        }
                    }
                }
            }

           //Before resolving check for the duplicates.
            _.uniqBy(datasetarr, function (data) {
                return data.accountID;
             });

            resolve(datasetarr);
        });
© www.soinside.com 2019 - 2024. All rights reserved.