get only the unique value of an array

后端 未结 5 1814
星月不相逢
星月不相逢 2021-01-14 09:16

I am new to javascript and I tried like using distinct but its not what im looking for

example array:

let arr = [ {key:\"1\",value:\"dog\"},
                 


        
5条回答
  •  星月不相逢
    2021-01-14 09:38

    You can use reduce and Map

    let arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}]
    
    let mapper = arr.reduce( (op,inp) => {
      let {key} = inp
      op.set(key, op.get(key) || {value: inp, count:0})
      op.get(key).count++
      return op
    },new Map())
    
    
    let final = [...mapper.values()].reduce((op,{value,count}) => {
       if(count === 1){
        op.push(value)
       }
       return op
    },[])
    
    console.log(final)

提交回复
热议问题