如何使用ImmutableJS计算List中的项目?

时间:2016-03-09 15:19:29

标签: javascript functional-programming immutable.js

我有一个如下所示的列表:

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

如何使用ImmutableJS运算符对这些项进行计数并获得一个如下所示的Map:

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

我在普通的JS中找到了以下函数here,那么我怎么能用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 个答案:

答案 0 :(得分:5)

尝试groupBy后跟map。像这样:

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

list.groupBy(elem => elem)将返回KeyedSeq,其中颜色字符串为其键,Iterable字符串为值。它在纯JS中看起来像这样。

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

然后我们可以映射这些以返回迭代的大小以及名称,我们应该得到你想要的东西:

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

当然,如果你想要得到这个,你最后需要使用toJS()

答案 1 :(得分:0)

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

list.toJS().length