vue 对象数组去重

vue 对象数组去重

1、利用set去重

其实很简单,一般的数组去重可以直接用 new Set() 方法即可,但是数组对象的话,比较复杂,不能直接用,我们可以采取间接的方法来去重

对象去重

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))
}

简单格式
代码如下(示例):

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))

————————————————
下面有一个示例,根据对象的id作为去重的依据:

<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));
      },

猜你喜欢

转载自blog.csdn.net/Min_nna/article/details/127356888
今日推荐