I have an array of objects with 3 keys, lat, lng and value. e.g.
let arr = [
{ lat: 20, lng: 30, value: 3 },
{ lat: 25, lng: 25, value: 4 },
{ lat: 20, lng: 30, value: 6 },
{ lat: 30, lng: 40, value: -5 },
{ lat: 25, lng: 25, value: 7 },
];
I'd like to compute the sum for each lat/lng pair, expecting the following result:
let res = [
{ lat: 20, lng: 30, value: 9 },
{ lat: 25, lng: 25, value: 11 },
{ lat: 30, lng: 40, value: -5 }
];
I have tried to store the results into an intermediate object, like this:
const temp = res.reduce((acc, { lat, lng, value }) => {
acc[lat] = acc[lat] || {};
acc[lat][lng] = acc[lat][lng] || 0;
acc[lat][lng] += value;
return acc;
}, {});
so temp would look like this:
let temp = {
20: {
30: 9
},
25: {
25: 11
},
30: {
40: -5
}
};
And then convert it to the format I want:
let res = Object.keys(temp).reduce((acc, lat) => {
let tt = Object.keys(temp[lat]).map(lng => {
return {lat: lat, lng: lng, value: temp[lat][lng]};
});
acc.push(...tt);
return acc;
}, []);
This looks highly inefficient and I'm sure there is a smarter way to do it. I have looked at lodash's groupBy and sumBy but I couldn't put a solution together.