1

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.

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

another possible solution with filter... .length
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.