How to count texts that are the same in a value

I have this string:

item_type = 'a, a, b'

How can I count the values so I would get something like this:

number_of_a = 2
number_of_b = 1

I tried something like below but got some JavaScript for input string “[object Object]” error

if(item_type != null) {
    item_type = item_type.split(",");
    item_type.forEach(function(x) {
        number_of_a[x] = (number_of_a[x] || 0) + 1;
    });
}

Answer

reduce is your friend, as with any grouping operation

const item_type = 'a, a, b';
const result = item_type.split(", ").reduce ( (a,i) => {
   a[i] = (a[i] +1 || 1)
   return a;
},{})

console.log(result);