I have below sample javascript array object –
JavaScript
x
9
1
[ {id:"B1",name:"Belacost",group:"Quim"},
2
{id:"B1",name:"Medtown",group:"Bik"},
3
{id:"B1",name:"Regkim",group:"Dum"},
4
{id:"C1",name:"CSet",group:"Core"},
5
{id:"D1",name:"Merigo",group:"Dian"},
6
{id:"D1",name:"Chilland",group:"Ground"},
7
{id:"N1",name:"Fiwkow",group:"Vig"},
8
]
9
In this array I want to make id as empty if it repeats.
JavaScript
1
9
1
Eg. [ {id:"B1",name:"Belacost",group:"Quim"}, //id is here since this is first time
2
{id:"",name:"Medtown",group:"Bik"}, //id is blank since we already have B1
3
{id:"",name:"Regkim",group:"Dum"},
4
{id:"C1",name:"CSet",group:"Core"},
5
{id:"D1",name:"Merigo",group:"Dian"}, // id is here since D1 is first time
6
{id:"",name:"Chilland",group:"Ground"}, //id is empty since we already have id D1
7
{id:"N1",name:"Fiwkow",group:"Vig"},
8
]
9
I tried to achive it through map , but could not find repeat id.
Advertisement
Answer
use reduce
method
JavaScript
1
23
23
1
const list = [ {id:"B1",name:"Belacost",group:"Quim"},
2
{id:"B1",name:"Medtown",group:"Bik"},
3
{id:"B1",name:"Regkim",group:"Dum"},
4
{id:"C1",name:"CSet",group:"Core"},
5
{id:"D1",name:"Merigo",group:"Dian"},
6
{id:"D1",name:"Chilland",group:"Ground"},
7
{id:"N1",name:"Fiwkow",group:"Vig"},
8
]
9
10
11
const result = list.reduce((acc, item ) => {
12
13
const isExisting = acc.some(i => i.id === item.id)
14
15
if(isExisting){
16
return [acc, {item, id: ""}]
17
}
18
19
return [acc, item]
20
21
}, [])
22
23
console.log(result)