0

假设我有一个这种形式的数组

[
   [val1,val2,val3],
   [val4,val2,val1]
   ....
]

更新-对不起,我对我的要求不太清楚。我的意思是这个

输出应该是这样的对象数组

[ {[val1,val2,val3] : 1}, {[val4,val2,val1] : 1}],

我刚刚意识到,上面的 json 非常愚蠢,我认为创建这样的对象更有意义

{ selectedRowIndices: [rows that have the value], freq: the frequency}

我想到了下划线并使用它的 groupBy 函数,实际上,使用简单的数组成功地做到了这一点,使用

groups = _(values)
  .chain()
  .groupBy(_.identity)
  .map((values, key) ->
    freq: values.length
    value: key
  ).sortBy((d) ->
    d.value
  ).value()

但是,我不确定如何使用上述数组。

4

2 回答 2

5

创建直方图还有一个更简单的函数:countBy. 如果您不想按身份分组,而是按每个数组的第三项分组,您可以编写

_.countBy( (a) -> a[2] )
于 2013-08-06T20:25:12.783 回答
0

我想你正在寻找

groups = _.chain(values)
  .groupBy((a) ->
    a[2]
  ).map((values, key) ->
    value: key // the third column
    selectedRows: values // the rows that have this value
    freq: values.length // and their number
  ).sortBy((d) ->
    d.value
  ).value()

如果您需要索引,则将groupBy调用替换为

  .reduce((m, a, i) ->
    k = a[2]
    (m[k] || m[k]=[]).push i // instead of pushing `a`
    m
   , {})
于 2013-08-06T20:37:34.627 回答