Home > Net >  Javascript object - Delete repeating id
Javascript object - Delete repeating id

Time:11-25

I have below sample javascript array object -

[ {id:"B1",name:"Belacost",group:"Quim"},
  {id:"B1",name:"Medtown",group:"Bik"},
  {id:"B1",name:"Regkim",group:"Dum"},
  {id:"C1",name:"CSet",group:"Core"},
  {id:"D1",name:"Merigo",group:"Dian"},
  {id:"D1",name:"Chilland",group:"Ground"},
  {id:"N1",name:"Fiwkow",group:"Vig"},
]

In this array I want to make id as empty if it repeats.

Eg. [ {id:"B1",name:"Belacost",group:"Quim"}, //id is here since this is first time
      {id:"",name:"Medtown",group:"Bik"}, //id is blank since we already have B1
      {id:"",name:"Regkim",group:"Dum"},
      {id:"C1",name:"CSet",group:"Core"},
      {id:"D1",name:"Merigo",group:"Dian"}, // id is here since D1 is first time
      {id:"",name:"Chilland",group:"Ground"}, //id is empty since we already have id D1
      {id:"N1",name:"Fiwkow",group:"Vig"},
    ]

I tried to achive it through map , but could not find repeat id.

CodePudding user response:

use reduce method

const list = [ {id:"B1",name:"Belacost",group:"Quim"},
  {id:"B1",name:"Medtown",group:"Bik"},
  {id:"B1",name:"Regkim",group:"Dum"},
  {id:"C1",name:"CSet",group:"Core"},
  {id:"D1",name:"Merigo",group:"Dian"},
  {id:"D1",name:"Chilland",group:"Ground"},
  {id:"N1",name:"Fiwkow",group:"Vig"},
]


const result = list.reduce((acc, item ) => { 
  
  const existinngItem = acc.find(i => i.id === item.id)
  
  if(existinngItem){
     return [...acc, {...item, id: ""}]
  }
  
  return [...acc, item]

}, [])

console.log(result)

CodePudding user response:

We can also do it with Array.map and Array.some()

let data = [ {id:"B1",name:"Belacost",group:"Quim"},
  {id:"B1",name:"Medtown",group:"Bik"},
  {id:"B1",name:"Regkim",group:"Dum"},
  {id:"C1",name:"CSet",group:"Core"},
  {id:"D1",name:"Merigo",group:"Dian"},
  {id:"D1",name:"Chilland",group:"Ground"},
  {id:"N1",name:"Fiwkow",group:"Vig"},
]

let result = data.map((e,i,a) =>{
  let exists = a.slice(0,i).some(d => d.id === e.id)
  e.id = exists? "": e.id
  return e
})
console.log(result)

  • Related