Home > OS >  Count frequency of specific value in JavaScript object
Count frequency of specific value in JavaScript object

Time:03-05

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.

CodePudding user response:

Using 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);

Another solution using Array#filter instead of 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);

CodePudding user response:

Another possible solution using filter and getting length of result

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)

  • Related