javascript - 从包含重复项的数组中获取唯一的 ObjectID
问题描述
所以我有一个 ObjectID 的数组,例如:
console.log(objectIdArray);
给[ObjectID, ObjectID, ObjectID]
.
但是,这里有重复项,如映射到 ID 字符串时所示:
var idArray = objectIdArray.map(objectId => objectId.toString());
console.log(idArray);
给出["5afa54e5516c5b57c0d43227", "5afa54e5516c5b57c0d43227", "5afa54f0516c5b57c0d43228"]
您可以看到以27结尾的 ID重复两次的位置。
如何过滤此 ObjectID 数组以删除重复项(保留完整的ObjectID对象,而不仅仅是 ID 字符串值)?
解决方案
const removeDuplicates = inputArray => {
const ids = [];
return inputArray.reduce((sum, element) => {
if(!ids.includes(element.toString()){
sum.push(element);
ids.push(element.toString());
}
return sum;
}, []);
};
此解决方案将删除不是具有特定 ID 的第一个对象的所有对象。
我们用 id 填充 an Array
,然后检查 id 是否已经填充到当前列表中。
如果有很多元素,上述解决方案可能会很慢,因为您需要检查每个迭代的O(n)inputArray
的 id 列表,这会将算法置于O(n^2)+O(n )
所以相反,我们可以先对它进行排序,toString()
然后我们可以验证当前 id 与我们看到的最后一个 id 不匹配。
const removeDuplicates = inputArray => {
const sortedArray = inputArray.sort((a,b) => (a.toString() > b.toString() ? 1 : (a.toString() < b.toString() ? -1 : 0)));
let lastSeen = undefined;
return sortedArray.reduce((sum, element) => {
if(lastSeen !== element.toString()){
sum.push(element);
}
lastSeen = element.toString();
return sum;
}, []);
};
现在算法是O(n log n) + O(n)假设排序使用合并排序
推荐阅读
- javascript - Streams API:可以撤消 .pipeTo()?
- azure-devops - 是否可以在 Azure DevOps 中为管道参数使用别名?
- macros - Bluestacks - 使用宏启动和退出应用程序
- pyomo - 预测模型、目标函数和优化
- pm2 - PM2 在 centos 8 上每 90 秒就会被杀死一次
- javascript - 在 JavaScript 中根据另一个数组对数组进行排序
- mysql - MySQL 多个 if 语句
- javascript - 如果两个对象值都存在于 javascript 中,请检查行号
- background-color - 如何更改背景颜色的不透明度 - BG-INFO Opacity
- r - 使用 purrr::map 应用于每个值