我们说我有一个这种形式的数组
[
[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()
但是,我不确定如何使用上面的数组。
答案 0 :(得分:4)
创建直方图有一个更简单的功能:countBy
。如果您不想按标识分组,而是按每个数组的第三项分组,则可以编写
_.countBy( (a) -> a[2] )
答案 1 :(得分: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
, {})