Use js to deduplicate array objects

foreword

Hello everyone, today I will share with you a few methods for deduplication of array objects. Deduplication of array objects is also often used, so I will share with you.

1. Array content

We first create an array, the following is the created array.

let arrs = [{
    
    
     id: '1',
     key: '1',
     value: '张三'
   }, {
    
    
     id: '3',
     key: '2',
     value: '李四'
   }, {
    
    
     id: '2',
     key: '3',
     value: '王五'
   }, {
    
    
     id: '1',
     key: '1',
     value: '赵六'
   }, {
    
    
     id: '1',
     key: '2',
     value: '马七'
}]

2. Removal method

1. Object access attribute method

The code is as follows (example):

let newArr = [];
    let obj = {
    
    };
    for (var i = 0; i < arrs.length; i++) {
    
    
       if (!obj[arrs[i].key]) {
    
    
         newArr.push(arrs[i])
         obj[arrs[i].key] = true
       }
    }
console.log(newArr);

2. Map() method

The code is as follows (example):

let map = new Map();
for (let item of this.arrs) {
    
    
    map.set(item.id, item);
 }
this.arrs = [...map.values()];
console.log(this.arrs)

The set method sets the key value corresponding to the key, and then returns the entire Map structure. If the key already has a value, the key value will be updated, otherwise the key will be newly generated.
The values ​​method can return the iterator object of the value of the Map object.

3. reduce() method

The reduce() method receives a function as an accumulator, and each value in the array (from left to right) is initially reduced to a value
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
insert image description here

const obj = {
    
    }
arr = arrs.reduce((total, next) => {
    
    
  obj[next.key] ? '' : obj[next.key] = true && total.push(next)
  return total
}, [])
console.log(arrs)

There is another requirement here. If there are two or more judgment conditions, deduplicate the array object and add a judgment condition.

const hasObj = {
    
    }
arrs = arrs.reduce((total, next) => {
    
    
   const filterKey = next.key + next.id;
   hasObj[filterKey] ? "" : hasObj[filterKey] = true && total.push(next)
   return total
}, [])
console.log(arrs)

Conclusion:

The above is the whole content of this chapter, I hope it can help you.

Guess you like

Origin blog.csdn.net/SqlloveSyn/article/details/129626971