Ben
Ben

Reputation: 493

Count frequency of specific value in JavaScript object

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.

Upvotes: 1

Views: 708

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28414

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

Upvotes: 3

cmgchess
cmgchess

Reputation: 10247

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)

Upvotes: 2

Related Questions