从包含重复项的数组中获取唯一的ObjectID

3

So I have an array of ObjectID's, for example:

console.log(objectIdArray);

得到[ObjectID,ObjectID,ObjectID]

但是这里有重复项,当映射到ID字符串时可以看到:

var idArray = objectIdArray.map(objectId => objectId.toString());
console.log(idArray);

给出了一个数组 ["5afa54e5516c5b57c0d43227", "5afa54e5516c5b57c0d43227", "5afa54f0516c5b57c0d43228"],可以看到以27结尾的ID被重复两次。

如何筛选这个对象ID数组以删除重复项(保留完整的ObjectID对象,而不仅仅是ID字符串值)?


我经常将数组的值添加到一个映射中(var map = {}; array.forEach(id => map[id] = true // or original object)),然后返回 Object.keys(map)Object.values(map)。时间复杂度为 O(n)。 - jrasm91
3个回答

3
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的第一个对象的对象。

我们使用Array填充ID,然后检查当前列表中是否已经填充了这些ID。


如果元素很多,则上述解决方案可能会潜在地变慢,因为您需要对inputArray中的每次迭代都进行O(n)的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),假设排序使用归并排序

0
如果你使用ES6,你可以采用Sajeetharan的方法,但是需要创建一组对象,而不是它们的id:
let nodupes = [...new Set(objectIdArray)];

它们可以用于任何东西:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set - Andrew Svietlichnyy
我不相信JavaScript Set可以使用完整的对象,请参见此处。执行上述操作并不会删除任何ObjectID。 - Kevin Novak
这是因为对象不是通过它们的内容进行比较,它们必须是指向同一个对象的引用。 - Andrew Svietlichnyy

0
我建议使用MongoDB聚合管道来避免最终结果具有重复的ObjectId值的情况。
然而:
// Define callback Function to receive modified Array
var receiveModifiedArray = function(objectIdArray) {
    // log modified Array to console
    console.log(objectIdArray);
}

// Remove duplicate ObjectId values
function removeDuplicateObjectIdValues(objectIdArray, callback) {

    // Iterate through each ObjectId
    objectIdArray.forEach((currentValue, index, array) => {
        // evaluate Array items with index greater than 0
        if(index > 0) {

            // check ObjectId string values for type and value equality
            if(currentValue.toString() == array[index -1].toString()) {
                /**
                 * The splice() method changes the contents of an array
                 * by removing existing elements and/or adding new elements.
                 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
                 */
                objectIdArray.splice(index,1);
            }

            // If processing last item in Array, callback
            if(index == array.length +1) {
                callback(objectIdArray);
            }
        }
    });

    // Return to move on to next message in call stack
    return;
}

// Remove duplicate ObjectId values
removeDuplicateObjectIdValues(objectIdArray,receiveModifiedArray);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接