js remove duplicate objects in array objects

Remove the duplicate objects in the array object. This situation is a frequently encountered requirement in the project. It is convenient to use it in the future to record it here:

1. De-duplicate according to an attribute in the object, take id as an example

Similar to the deduplication of an array, you can use indexOf, include, lastIndexOf, find, etc., here only indexOf is used to achieve it.

let arr = [
	{
    
    id:1, name:'test', status:'success'},
	{
    
    id:2, name:'dev', status:'success'},
	{
    
    id:3, name:'prod', status:'fail'},
	{
    
    id:4, name:'sand', status:'waiting'},
	{
    
    id:3, name:'box', status:'running'},
	{
    
    id:2, name:'dev', status:'success'}
]
function objHeavy(arr){
    
    
	let arr1 = []; //存id
	let newArr = []; //存新数组
	for(let i in arr){
    
    
		if(arr1.indexOf(arr[i].id) == -1){
    
    
			arr1.push(arr[i].id);
			newArr.push(arr[i]);
		}
	}
	return newArr;
}

result:
Insert picture description here

2. Only duplicate identical objects (attributes and attribute values ​​are the same)

The general idea is as follows:
First, loop the array to get the array composed of all the properties of the object;
second, loop the property array to concatenate the properties of the object and the corresponding value into a string;
then, use the hasOwnProperty method to determine whether the string is an object obj If it is not, use this string as the attribute, and add a new attribute to the obj object if true is the value;
finally, continue to loop to determine the next object;

let arr = [
	{
    
    id:1, name:'test', status:'success'},
	{
    
    id:2, name:'dev', status:'success'},
	{
    
    id:3, name:'prod', status:'fail'},
	{
    
    id:4, name:'sand', status:'waiting'},
	{
    
    id:3, name:'prod', status:'fail'},
	{
    
    id:2, name:'dev', status:'success'}
]
function objHeavy(arr){
    
    
	var newArr= []; //存新数组
    var obj= {
    
    }; //存处理后转成字符串的对象
    for (var i = 0; i < arr.length; i++) {
    
    
        var keys = Object.keys(arr[i]);
        keys.sort(function(a, b) {
    
    
            return (Number(a) - Number(b));
        });
        var str = '';
        for (var j = 0; j < keys.length; j++) {
    
    
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(arr[i][keys[j]]);
        }
        if (!obj.hasOwnProperty(str)) {
    
    
            newArr.push(arr[i]);
            obj[str] = true;
        }
    }
    return newArr;
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/112562702