Reputation: 1354
I have an array of object
const array = [
{keyA: "HG 386893", count: 1, type: "dha"},
{keyA: "AL 386893", count: 1, type: "gop"},
{keyA: "HG 386893", count: 2, type: "ind"},
{keyA: "NC 386893", count: 1, type: "dha"},
{keyA: "HG 386893", count: 1, type: "gop"},
{keyA: "RO 386893", count: 1, type: "ind"}
];
I want to merge keys based on similar keyA
property and concat type
and add count
. So final result will be:
const result = [
{keyA: "HG 386893", count: 4, type: "dha,ind,gop"},
{keyA: "AL 386893", count: 1, type: "gop"},
{keyA: "NC 386893", count: 1, type: "dha"},
{keyA: "RO 386893", count: 1, type: "ind"}
];
The way I am implementing this is:
keyA
count
and concat type
I know this is not an optimal solution, so I need some help to optimize this in better way. Thanks!
Upvotes: 2
Views: 54
Reputation: 22370
You could use a Map for O(n) time complexity:
const array = [
{keyA: "HG 386893", count: 1, type: "dha"},
{keyA: "AL 386893", count: 1, type: "gop"},
{keyA: "HG 386893", count: 2, type: "ind"},
{keyA: "NC 386893", count: 1, type: "dha"},
{keyA: "HG 386893", count: 1, type: "gop"},
{keyA: "RO 386893", count: 1, type: "ind"}
];
//console.log(array);
const groupedByKeyA = new Map();
for (const obj of array) {
if (groupedByKeyA.has(obj.keyA)) {
const currentType = groupedByKeyA.get(obj.keyA).type;
groupedByKeyA.get(obj.keyA).type = `${currentType},${obj.type}`
} else {
groupedByKeyA.set(obj.keyA, obj);
}
}
//console.log(groupedByKeyA);
const groupedArray = Array.from(groupedByKeyA.values());
console.log(groupedArray);
Upvotes: 0
Reputation: 28414
You can use .reduce
:
const array = [
{ keyA: "HG 386893", count: 1, type: "dha" },
{ keyA: "AL 386893", count: 1, type: "gop" },
{ keyA: "HG 386893", count: 2, type: "ind" },
{ keyA: "NC 386893", count: 1, type: "dha" },
{ keyA: "HG 386893", count: 1, type: "gop" },
{ keyA: "RO 386893", count: 1, type: "ind" }
];
const grouped = Object.values(array.reduce((acc,item) => {
const { keyA, count, type } = item;
const prev = acc[keyA];
acc[keyA] = prev
? { ...item, count: prev.count+count, type: `${prev.type},${type}` }
: item;
return acc;
}, {}));
console.log(grouped);
Upvotes: 2