Reputation: 125
I'm have array duplicate data. I need group array Come together
const data = [
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0002" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0004" }
];
I need group duplicate data. Come together And have only one like this >>
const res = [
{ id: 1, name: "john", card: [{ cardId: "0001" }, { cardId: "0002"} ] },
{ id: 2, name: "poul", card: [{ cardId: "0003" }, { cardId: "0004"} ] }
];
Thank You Very Much for help.
Upvotes: 0
Views: 58
Reputation: 35261
You could use reduce
to group the items based on name
. Create a Set
property called card
to get unique cardId
s for each name
. Then loop through the set to create the output
const data = [
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0002" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0004" }
];
const merged = data.reduce((r, { id, name, cardId }) => {
r[name] = r[name] || { id, name, card: new Set };
r[name].card.add(cardId)
return r;
}, {})
const output = Object.values(merged).map(({ card, id, name }) =>
({ id, name, card: [...card].map(cardID => ({ cardID })) }) )
console.log(output)
Upvotes: 1
Reputation: 1179
var data = [
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0002" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0004" }
];
var res = [];
data.forEach(a => {
var searchResultInRes = res.find(x => x.id == a.id);
if (searchResultInRes) {
if (!searchResultInRes.card.some(x => x.cardId == a.cardId)) {
searchResultInRes.card.push({ cardId: a.cardId });
}
} else {
res.push({ id: a.id, name: a.name, card: [{ cardId: a.cardId }] });
}
});
console.log(res);
Upvotes: 1
Reputation: 11604
const data =
[{id: 1, name: 'john', cardId: '0001'}, {id: 1, name: 'john', cardId: '0001'},
{id: 1, name: 'john', cardId: '0002'}, {id: 2, name: 'poul', cardId: '0003'},
{id: 2, name: 'poul', cardId: '0003'}, {id: 2, name: 'poul', cardId: '0004'}];
let grouped = data.reduce((acc, {id, name, cardId}) => {
let d = acc.find(d => d.id === id);
if (!d)
acc.push({id, name, card: [cardId]});
else if (!d.card.includes(cardId))
d.card.push(cardId);
return acc;
}, []);
console.log(grouped);
Upvotes: 0