Vue object array deduplication

Vue object array deduplication

1. Use set to deduplicate

In fact, it is very simple. For general array deduplication, you can directly use the new Set() method, but for array objects, it is more complicated and cannot be used directly. We can use an indirect method to deduplicate

Object deduplication

unique(arr) {
    
     // 根据唯一标识id来对数组进行过滤
  const res = new Map();//定义常量 res,值为一个Map对象实例
  //返回arr数组过滤后的结果,结果为一个数组   过滤条件是,如果res中没有某个键,就设置这个键的值为1
  return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
}

The simple format
code is as follows (example):

function arr1(arr) {
    
    
    return Array.from(new Set(arr))
}
var arr = [1, 1, 1, 2, 2, 3, 4, 5, 6, 3, 4, 2, 4, 1,];
console.log(arr1(arr))

—————————————————
Here is an example, based on the id of the object as the basis for deduplication:

<el-button type="primary" size="medium" @click="quChong()">点击</el-button>
quChong() {
    
    
        let arr = [
          {
    
    
            id: 1,
            name: '111'
          },
          {
    
    
            id: 1,
            name: '111'
          },
          {
    
    
            id: 2,
            name: '222'
          },
          {
    
    
            id: 3,
            name: '333'
          }
        ];
        console.log(arr);
        console.log('--------------------');
        let arr1 = this.unique(arr);
        console.log(arr1);
      },
      unique(arr) {
    
    
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
      },

Guess you like

Origin blog.csdn.net/Min_nna/article/details/127356888