I am trying to sum values from different objects. Each object has its ID, but the IDs can repeat in some objects. What I need to do now is sum the values from the objects that have the same ID.
Does someone have an idea for me? I tried to use mongoose aggregate, but with no success.
Let’s suppose I have the objects below.
const array = [
{ _id: "123456", value: 30 },
{ _id: "123456789123456789", value: 12 },
{ _id: "123456", value: 25 },
];
I would need something that brings up the following result:
==> id: 123456
value: 55
==> id: 123456789123456789
value: 12
3
Answers
Reduce the array into a map. Conveniently,
map.set
returns the map, so it’s just a one-liner.Confused about syntax? See nullish coalescing and spread syntax. You can also convert the map into a plain object if you wanted to.
its impossible to have duplicate _id in mongodb, but you can change that to something like
dataId, id
or elseexample:
then with wongo would be like:
MONGO-PLAYGROUND
Note: if some data can be handle by resources/database, use it instead. otherwise, create a function to handle it.
For each object, it checks whether the "result" object already has a property with the same _id as the current object being looped over.