计算 JavaScript 对象中特定值的频率
我有一个结构如下的 JavaScript 对象:
var subject = {all: "inactive",firstSingular: "active", secondarySingular: "inactive",thirdSingular: "active",firstPlural: "inactive", secondaryPlural: "inactive",thirdPlural: "inactive"
我想计算该对象内“active”值的实例数(即返回2)。我当然可以编写一个函数来迭代对象并计算值,尽管我想知道是否有更简洁的方法在 JavaScript 中执行此操作(在 1 行中),类似于 python 中的 collections.Counter 函数。
I have a JavaScript object that is structured as such:
var subjects = {all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive"
I would like to count the instances of the "active" value within this object (i.e return 2). I could certainly write a function that iterates through the object and counts the values, though I was wondering if there was a cleaner way to do this (in 1 line) in JavaScript, similar to the collections.Counter function in python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
Object#values
和Array#reduce
:使用
Array#filter< 的另一个解决方案/code>
而不是减少:
Using
Object#values
andArray#reduce
:Another solution using
Array#filter
instead of reduce:另一种可能的解决方案是使用
filter
并获取结果的长度Another possible solution using
filter
and getting length of result