简体   繁体   中英

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;

        }, {})
 }

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.

您还可以使用混合解决方案:

list.toJS().length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM