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.
Advertisement
Answer
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 isExisting = acc.some(i => i.id === item.id) if(isExisting){ return [...acc, {...item, id: ""}] } return [...acc, item] }, []) console.log(result)