I am trying to group an array of objects based on the value of the first item below:
const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"value":"value3","metric":1}];
const result = [...data.reduce((acc, obj) => {
const key = obj.value;
const item = acc.get(key) || Object.assign({}, obj, {
metric: 0,
});
item.metric += obj.metric;
return acc.set(key, item);
}, new Map).values()];
console.log(result);
However, I am facing difficulties when dealing with an array of arrays of objects like this:
[[{"value":"value1","formattedValue":"value1"},{"value":2831.8,"formattedValue":"283,180.00 %"}],[{"value":"value1","formattedValue":"value1"},{"value":349.1111111111111,"formattedValue":"34,911.11 %"}],[{"value":"value2","formattedValue":"value2"},{"value":3.3703703703703702,"formattedValue":"337.04 %"}]]
The difference here is that instead of a single object like this:
{"value":"value1","metric":1}
We now have an array of objects like this:
[{"value":"value1","formattedValue":"value1"},{"value":"1.0","formattedValue":100.00 %}]
An approach could be transforming the second query to match the format of the first one, but I would like to find a solution while using the function previously mentioned.
The desired output should look like this:
[[{"value":"value1","formattedValue":"value1"},{"value":3180.91111111,"formattedValue":"318091.11 %"}],[{"value":"value2","formattedValue":"value2"},{"value":3.3703703703703702,"formattedValue":"337.04 %"}]]