gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:50:01 26 4
gpt4 key购买 nike

在插入数组之前尝试检查多个字段是否重复时,我遇到了一些问题。我想做的是从 firebase 检索,在插入 array 之前检查 accountIDsubtype 字段通过 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 和相同子类型的重复项。有办法解决这个问题吗?

谢谢!

最佳答案

find如果没有出现您的数据,则返回undefined;所以你要做的就是检查返回的值是否未定义,然后进行计算

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

关于Javascript 在插入数组之前检查重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47919716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com