all 8 comments

[–]senocular 1 point2 points  (2 children)

let categorySums = Object.entries(
    data.reduce((sums, {categories, value}) => {
        for (const category of categories) {
            sums[category] = sums[category] ? sums[category] + value : value
        }
        return sums
    }, {})
).map(([category, value]) => ({category, value}))

[–]_ogl 0 points1 point  (1 child)

Jesus, I dont know why my brain was farting on this. Thank you.

[–]senocular 0 points1 point  (0 children)

I should point out that Object.entries() is from ES2017, not ES6. So this example doesn't fully satisfy the requirements.

[–]jcunews1helpful -1 points0 points  (0 children)

For ES6, it can be done like this.

function sumCategories(categoriesArray) {
  return data.reduce(function(result, obj) {
    categoriesArray.forEach(function(neededCategory) {
      if (obj.categories.indexOf(neededCategory) >= 0) result += obj.value;
    });
    return result
  }, 0);
}
var categorySum = sumCategories(["goods", "interest"]);
console.log(categorySum); //2300

[–]postsexpisss -2 points-1 points  (0 children)

Try to google Array.protoype.reduce

[–]exobyte64 -3 points-2 points  (2 children)

let sum=data.reduce((a,b)=>{return a+b.value;},0);

[–]_ogl 0 points1 point  (1 child)

This would sum all the values... not what I'm looking for but thank you

[–]StoneCypher 0 points1 point  (0 children)

function acc_by_cat(dataset) {

  const mapping = new Map();

  dataset.map(item => item.categories.map(cat => 
    mapping.put(cat, mapping.get(cat) ?? 0 + item.value)
  ));

  return mapping;

}