Search code examples
javascriptobjectcounterfrequency

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.


Solution

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