js去重

1、数组对象去重

(1)根据某属性去重

let data = [ { name: 'ws', id: 1 }, { name: 'cj', id: 2 }, { name: 'jf', id: 3 }, { name: 'll', id: 1 }, { name: 'wwx', id: 2 }, { name: 'ws', id: 3 } ]
let obj={}
let newArr = data.reduce((item,next)=>{
  //根据id去重
  if(!obj[next.id]){
    obj[next.id]=true
    item.push(next)
  }
  return item
},[])
console.log(newArr )

(2)去除重复对象

function deleteObj(itemArr){
  var arr=[]
  var newObj={}
  for(var i = 0;i < itemArr.length;i++){
    var keys=Object.keys(itemArr[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(itemArr[i][keys[j]])
    }
    if(!newObj.hasOwnProperty(str)){
       arr.push(itemArr[i])
       newObj[str]=true
    }
   }
  return arr
}
const data=[
  {name:'xl',age:12},
  {name:'xl',age:12},
  {name:'xlccc',age:12},
  {name:'xlssss',age:12},
]

console.log(deleteObj(data))

2、数组去重

(1)es6

var arr=[1,2,4,5,6,7,7,8,4,21]
arr = [...new Set(arr)]
console.log(arr)

(2)reduce

let arr = ['x','w','s','r','t','x','j','v','a']
let newArr=arr.reduce(function(a,current){
  if(a.indexOf(current)===-1){
    a.push(current)
  }
  return a
},[])
console.log(newArr)

(3)filter

const array  = [2,3,4,5,3,2,13,23];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);

 

上一篇:解决主从架构的redis分布式锁主节点宕机锁丢失的问题


下一篇:CPU 被挖矿,Redis 竟是内鬼