Map and Reduce JSON Objects with JavaScript
I tried to do with better time complexity:
let ans = [];
let map = new Map();
ques.cells.forEach(x => {
if(map[x.geo__name]){
map.set(x.geo__name, map[x.geo__name] + x.gdp_growth__avg);
}else{
map.set(x.geo__name,x.gdp_growth__avg);
}
});
map.forEach((v,k)=>{
ans.push({"geo__name":k, "gdp_growth__avg":v});
});
ques.cells = ans;
with solution looking like this:
[
{
"geo__name": "united states of america",
"gdp_growth__avg": 3.79848988541973
},
{
"geo__name": "china",
"gdp_growth__avg": 10.0085233990531
},
{
"geo__name": "russia",
"gdp_growth__avg": -4.14352840666389
},
{
"geo__name": "botswana",
"gdp_growth__avg": -8.66854034194856
}
]
The Array.reduce
method doesn't change the array object, it returns the results in a new array.
Try this:
var data = { cells:[...] };
var r = data.cells.reduce(function(pv, cv) {
if ( pv[cv.geo__name] ) {
pv[cv.geo__name] += cv.gdp_growth__avg;
} else {
pv[cv.geo__name] = cv.gdp_growth__avg;
}
return pv;
}, {});
console.log(r);
Output example:
{
'united states of america': 18.76051995774611,
'china': 71.39814330096999,
'russia': -36.291297610751,
'botswana': -8.730754563729707
}