【问题标题】:How to count items in List with ImmutableJS?如何使用 ImmutableJS 计算 List 中的项目?
【发布时间】:2016-06-24 01:31:36
【问题描述】:

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

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

我如何使用 ImmutableJS 运算符来计算这些项目并获得可能如下所示的 Map:

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

我发现下面的函数 here 可以在普通 JS 中做到这一点,那么我如何使用 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;

        }, {})
 }

【问题讨论】:

    标签: javascript functional-programming immutable.js


    【解决方案1】:

    尝试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()

    【讨论】:

    • 谢谢!希望@ThorbenA 也这样做! :D
    【解决方案2】:

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

    list.toJS().length
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      相关资源
      最近更新 更多