宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

在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;
}

有人在微信里提到stringify,但我考虑到它没法处理{x:1,Y;2},{Y:2,x:1}这种情况,所以一开始没注意,但它有第二个参数,很好用。
stringify 函数第二个参数的妙用

还是上面这道题,我们可以在第二个参数上解决对象属性的顺序问题,给它加上一个数组[‘name’,’author’],代码改为下面这个就没问题了。
记得第二个参数数组里要包含所有对象的属性进去哦。

function unique(arr) {
	let unique = {};
	arr.forEach(function(item) {
		unique[JSON.stringify(item,['name','author'])] = item; //键名顺序问题
	})
	arr = Object.keys(unique).map(function(u) {
		//Object.keys()返回对象的所有键值组成的数组,map方法是一个遍历方法,返回遍历结果组成的数组.将unique对象的键名还原成对象数组
		return JSON.parse(u);
	})
	return arr;
}