计算 JavaScript 对象中特定值的频率
Count frequency of specific value in JavaScript object
我有一个 JavaScript 对象,其结构如下:
var subjects = {all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive"
我想计算此对象中“活动”值的实例数(即 return 2)。我当然可以编写一个函数来遍历对象并对值进行计数,尽管我想知道在 JavaScript 中是否有更简洁的方法(在 1 行中)执行此操作,类似于 collections.Counter 函数在 python.
使用Object#values
and Array#reduce
:
const subjects = { all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive" };
const count = Object.values(subjects).reduce((total, value) => value === 'active' ? total + 1 : total, 0);
console.log(count);
另一个使用 Array#filter
而不是 reduce 的解决方案:
const subjects = { all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive" };
const count = Object.values(subjects).filter(value => value === 'active').length;
console.log(count);
另一种可能的解决方案,使用 filter
并获取结果的长度
var subjects = {all: "inactive", firstSingular: "active",secondSingular:"inactive", thirdSingular: "active", firstPlural: "inactive",secondPlural: "inactive", thirdPlural: "inactive"}
var res = Object.values(subjects).filter((val) => val === 'active').length
console.log(res)
我有一个 JavaScript 对象,其结构如下:
var subjects = {all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive"
我想计算此对象中“活动”值的实例数(即 return 2)。我当然可以编写一个函数来遍历对象并对值进行计数,尽管我想知道在 JavaScript 中是否有更简洁的方法(在 1 行中)执行此操作,类似于 collections.Counter 函数在 python.
使用Object#values
and Array#reduce
:
const subjects = { all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive" };
const count = Object.values(subjects).reduce((total, value) => value === 'active' ? total + 1 : total, 0);
console.log(count);
另一个使用 Array#filter
而不是 reduce 的解决方案:
const subjects = { all: "inactive", firstSingular: "active", secondSingular: "inactive", thirdSingular: "active", firstPlural: "inactive", secondPlural: "inactive", thirdPlural: "inactive" };
const count = Object.values(subjects).filter(value => value === 'active').length;
console.log(count);
另一种可能的解决方案,使用 filter
并获取结果的长度
var subjects = {all: "inactive", firstSingular: "active",secondSingular:"inactive", thirdSingular: "active", firstPlural: "inactive",secondPlural: "inactive", thirdPlural: "inactive"}
var res = Object.values(subjects).filter((val) => val === 'active').length
console.log(res)