How to count items in List with ImmutableJS?

Viewed 1351

I have a List which looks like this:

["green", "blue","green","green", "blue", "black"]

How can I use the ImmutableJS operators to count these items and get a Map which could look like this:

{ green: {name: green, count: 3}, blue:{name: blue, count: 2}, black:{name: black, count: 1}}

I found the following function here to do just that in plain JS, so how could I achieve this with ImmutableJS?

export const countOccurances = obj => {

   return obj
        .reduce((counter, x) =>  {

            if (counter.hasOwnProperty(x)) { 
                counter[x].count = counter[x].count + 1
            } else {
                counter[x] =  {name: x, count: 1}
            }
            return counter;

        }, {})
 }
2 Answers

You could also use a mixed solution:

list.toJS().length
Related