使用ruby在数组中过滤频繁项

Posted

技术标签:

【中文标题】使用ruby在数组中过滤频繁项【英文标题】:frequent item filter in array using ruby 【发布时间】:2013-05-26 22:26:26 【问题描述】:
total =["a","a","a","b","b","b","b","b","b","b","b","c","c","c","d","d","d","d","d","d","d","d","b","b","e","e","e","e","e","f"]

smart_total = total.group_by|i| i.map|i,j| [i,j.length]
smart_total = [["a", 3], ["b", 10], ["c", 3], ["d", 8], ["e", 5], ["f", 1]]

我有样本数组

sample1 = ["a","f","b"]

根据最大频繁项,最终输出应该是一个元素,这里是b

sample2 = ["a","c"]

此处的输出可以是ac

我正在寻找类似的东西

result1 = sample1.magik_function
=>"b"

【问题讨论】:

【参考方案1】:
sample1.max_by|c| total.count(c) # => "b"
sample2.max_by|c| total.count(c) # => "a"

【讨论】:

以上是关于使用ruby在数组中过滤频繁项的主要内容,如果未能解决你的问题,请参考以下文章

Vue JS按多个数组对象项过滤

从两个数组中过滤重复项

使用 NSPredicate 根据数组属性过滤 CoreData 项列表

使用 Jquery Each 在 Javascript 对象和数组中查找匹配项

如何根据MongoDB中文档字段中的每个数组项过滤集合

PHP 过滤对象数组并返回新的对象数组,同时基于一个属性删除重复项