正在进行数据迁移/过滤项目,我不得不根据自身检查对象数组(所有对象都具有相同的架构)。
我有一种直觉,认为这段代码实际上并没有获取所有重复项,而我为数组建立索引的方式却导致某些内容完全被遗漏了。
这是我的原始代码:
const dedupeAdnsfCustomers = (adnsflist, listName) => {
let newList = [];
let filtered;
for (let index = 0; index < adnsflist.length; index++) {
filtered = adnsflist.filter(
x => x.CustomerID === adnsflist[index].CustomerID
);
if (filtered.length > 1) {
filtered.forEach(f => {
newList.push(f);
adnsflist.splice(adnsflist.indexOf(f), 1);
});
}
}
//following block was due to it appearing that it would
//remove all of the items from the original array...
//adding back only one ??
if (newList.length > 0) {
for (let index = 0; index < newList.length; ) {
filtered = newList.filter(
x => x.CustomerId === newList[index].CustomerId
);
adnsflist.unshift(filtered[0]);
index = index + filtered.length;
}
}
console.log(newList);
console.log(adnsflist);
return { originalList: adnsflist, internalDupes: newList, tag: listName };
};
我认为需要这样重写:
const dedupeAdnsfCustomers = (adnsflist, listName) => {
let newList = [];
let filtered;
adnsflist.forEach(adnsfItem => {
filtered = adnsflist.filter(x => x.CustomerID === adnsfItem.CustomerID);
if(filtered.length>0){
filtered.forEach(f => {
newList.push(f);
adnsflist.splice(adnsflist.indexOf(f), 1);
});
}
}
return {originalList: adnsflist, internalDupes: newList, tag: list};
});
只保留其中一个,并复制所有副本吗?