'Group keys of an object in array [closed]
I have an array :
let x = [{name: 'x1', value: 2}, {name: 'x2', value: 3}, {name: 'y1', value: 4}, {name: 'z1', value: 1}];
I need to group few keys based on some condition and get their sum
res = [{
name: ['x1, y1'],
value: 6
},
{
name: [x2],
value: 3
},
{
name: [z1],
value: 1
}]
Solution 1:[1]
You can take a number of grouped items and consider them as separate groups.
const
groups = [['x1', 'y1']],
data = [{ name: 'x1', value: 2 }, { name: 'x2', value: 3 }, { name: 'y1', value: 4 }, { name: 'z1', value: 1 }],
result = Object.values(data.reduce((r, { name, value }) => {
const key = groups.find(a => a.includes(name))?.join('|') || name;
r[key] ??= { name: [], value: 0 };
r[key].name.push(name);
r[key].value += value;
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution 2:[2]
You can do that this way:
let res = [
{
name: ["x1", "y1"],
value: 0
},
[...]
]
res.forEach(group => {
x.forEach(row => {
if (group.name.indexOf(row.name) !== -1) {
group.value += row.value;
}
});
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
| Solution 2 | Maneal |
