首页 > 解决方案 > 从包含重复项的数组中获取唯一的 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 字符串值)?

标签: javascriptmongoose

解决方案


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)假设排序使用合并排序


推荐阅读