ThorbenA
ThorbenA

Reputation: 1933

How to count items in List with ImmutableJS?

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;

        }, {})
 }

Upvotes: 4

Views: 1468

Answers (2)

jjyepez
jjyepez

Reputation: 350

You could also use a mixed solution:

list.toJS().length

Upvotes: 1

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

Try groupBy followed by map. Something like this:

list.groupBy(elem => elem).map(arr => {
    return  {"name" : arr.get(0), "count": arr.size }
})

list.groupBy(elem => elem) will return a KeyedSeq with the color String as it's key and an Iterable of Strings as value. It would look like this in pure JS.

{ green: ["green","green","green"], blue:["blue","blue"], black: ["black"]}

We can then map these to return the size of the iterable as well as the name and we should get what you wanted:

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

Of course if you wanted to get exactly that, you would need to use toJS() at the end.

Upvotes: 5

Related Questions