Drill

ProblemsJavaScript › data

Totals per category

mediumdataJavaScript

A ledger groups every sale under its category so each bucket shows a single sum.

sumPerCategory(sales: list<Sale>) → map<string, int>

Solve it in the editor →

Where you start

function sumPerCategory(sales) {
  
}

Worked examples

CallResult
sumPerCategory([{"category":"food","amount":10},{"category":"food","amount":15}]){"food":25}
sumPerCategory([{"category":"a","amount":3},{"category":"b","amount":4},{"category":"a","amount":5}]){"a":8,"b":4}
sumPerCategory([{"category":"x","amount":1}]){"x":1}
sumPerCategory([{"category":"p","amount":0},{"category":"q","amount":-2}]){"p":0,"q":-2}

Hint

Aggregate into a map keyed by category, adding each amount as you go.

Reference solution in JavaScript
function sumPerCategory(sales) {
  const result = new Map();
  for (const s of sales) {
    if (result.has(s.category)) result.set(s.category, result.get(s.category) + s.amount);
    else result.set(s.category, s.amount);
  }
  return result;
}

The same problem in another language

More data problems in JavaScript