从一个数组中移除重复对象

在JavaScript项目实践中,我们可能会经常需要移除重复对象的例子,本文通过一个案例来详细解答,并给出了最优解,希望对你有所帮助。

假设有下面这个数组对象,让你来删除重复项:

const books = [
    {
        name: "My Sister the Serial Killer",  
        author: "Oyinkan Braithwaite" 
    },
    {
        name: "Educated",  
        author: "Tara Westover" 
    },
    {
        name: "My Sister the Serial Killer",  
        author: "Oyinkan Braithwaite" 
    }
];

数组中的第一个对象和最后一个对象是相同的。那么,如果我们想从数组中删除这样的重复对象怎么办?令人惊讶的是,这是一个相当难解决的问题。为了了解原因,让我们来看看如何从一个数组中删除重复的对象,如字符串等平面项的数组中删除重复的对象。

首先,我们先来看一个简单的数组去重。

const strings = [
    "My Sister the Serial Killer", 
    "Educated", 
    "My Sister the Serial Killer"
];

如果我们想从这个数组中删除任何重复的项目,我们可以使用filter()方法和indexOf()方法来检查任何给定的项目是否是重复的。

const filteredStrings = strings.filter((item, index) => {
    // Return to new array if the index of the current item is the same
    // as the first occurence of the item
    return strings.indexOf(item) === index;
});

因为strings.indexOf(项)总是会返回该项的第一个出现的索引,所以我们可以判断当前在过滤循环中的项是否是重复的。如果是,我们就不返回到由filter()方法创建的新数组中。

对象并不像上面这么简单

这个相同的方法对对象不起作用的原因是,任何2个具有相同属性和值的对象实际上并不被认为是相同的。

const a = {
    name: "My Sister the Serial Killer",  
    author: "Oyinkan Braithwaite" 
};
const b = {
    name: "My Sister the Serial Killer",  
    author: "Oyinkan Braithwaite" 
};
a === b // false

这是因为比较对象是基于引用而不是结构来进行比较的。在比较对象时,不会考虑两个对象的属性和值是否相同的事实。因此,在一个对象数组中的indexOf(object)总是会返回所传递的对象的索引,即使存在另一个属性和值完全相同的对象。

我的解决方案是

鉴于这些信息,检查两个对象是否具有相同的属性和值的唯一方法就是实际检查每个对象的属性和值。我想出的解决方案是手动检查,但是为了提高性能和减少不必要的嵌套循环,我做了一些改动。

特别是,我做了3件事情

1.只检查数组中的每一个项目和后面的每一个项目,以避免对同一对象进行多次比较

2.只检查未发现与其他物品重复的物品

3.在检查每个属性的值是否相同之前,先检查两个对象是否有相同的键值

下面是最后的解决方法

function removeDuplicates(arr) {
    const result = [];
    const duplicatesIndices = [];
    // Loop through each item in the original array
    arr.forEach((current, index) => {
        if (duplicatesIndices.includes(index)) return;
        result.push(current);
        // Loop through each other item on array after the current one
        for (let comparisonIndex = index + 1; comparisonIndex < arr.length; comparisonIndex++) {
            const comparison = arr[comparisonIndex];
            const currentKeys = Object.keys(current);
            const comparisonKeys = Object.keys(comparison);
            // Check number of keys in objects
            if (currentKeys.length !== comparisonKeys.length) continue;
            // Check key names
            const currentKeysString = currentKeys.sort().join("").toLowerCase();
            const comparisonKeysString = comparisonKeys.sort().join("").toLowerCase();
            if (currentKeysString !== comparisonKeysString) continue;
            // Check values
            let valuesEqual = true;
            for (let i = 0; i < currentKeys.length; i++) {
                const key = currentKeys[i];
                if ( current[key] !== comparison[key] ) {
                    valuesEqual = false;
                    break;
                }
            }
            if (valuesEqual) duplicatesIndices.push(comparisonIndex);
        } // end for loop
    }); // end arr.forEach()
    return result;
}

如果文章对你有帮助,点个在看,谢谢!

好文和朋友一起看~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值