I have a previous solution that combined a count, based on a single matching value within an array of objects:
EG:
[
{
"ui5": "sap.m.Bar",
"count": 2
},
{
"ui5": "sap.m.Bar",
"count": 1
},
{
"ui5": "sap.m.Panel",
"count": 1
}
]
Will become:
[
{
"ui5": "sap.m.Bar",
"count": 3
},
{
"ui5": "sap.m.Panel",
"count": 1
}
]
With the code:
var r = {};
myArray.forEach(function (o) {
r[o.ui5] = (r[o.ui5] || 0) + o.count;
})
var outputArray = Object.keys(r).map(function (k) {
return { ui5: k, count: r[k] }
});
However, I am not sure how to compare a more detailed object, based on two matching values!
EG:
[
{
"ui5": "sap.m.Bar",
"_sMutator": "setCustomHeader",
"count": 2
},
{
"ui5": "sap.m.Bar",
"_sMutator": "addContent",
"count": 1
},
{
"ui5": "sap.m.Bar",
"_sMutator": "setCustomFooter",
"count": 3
},
{
"ui5": "sap.m.Bar",
"_sMutator": "setCustomFooter",
"count": 1
}
]
Will be reduced down to the expected output:
[
{
"ui5": "sap.m.Bar",
"_sMutator": "setCustomHeader",
"count": 2
},
{
"ui5": "sap.m.Bar",
"_sMutator": "addContent",
"count": 1
},
{
"ui5": "sap.m.Bar",
"_sMutator": "setCustomFooter",
"count": 4
}
]
I don't think I can expand my original logic to account for two matching values? Any help would be appriciated!
You could take an array with wanted keys for grouping and use this array for getting a joined key for the group and for getting an object if no object is assigned to the group property.
const
data = [{ ui5: "sap.m.Bar", _sMutator: "setCustomHeader", count: 2 }, { ui5: "sap.m.Bar", _sMutator: "addContent", count: 1 }, { ui5: "sap.m.Bar", _sMutator: "setCustomFooter", count: 3 }, { ui5: "sap.m.Bar", _sMutator: "setCustomFooter", count: 1 }],
keys = ['ui5', '_sMutator'],
result = Object.values(data
.reduce((r, o) => {
const key = keys.map(k => o[k]).join('|');
r[key] ??= {
...Object.fromEntries(keys.map(k => [k, o[k]])),
count: 0
};
r[key].count += o.count;
return r;
}, {})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }