1

I have the following array of objects

const users = [
 { name: 'Bob Johnson', occupation: 'Developer' },
 { name: 'Joe Davidson', occupation: 'QA Tester' },
 { name: 'Kat Matthews', occupation: 'Developer' },
 { name: 'Ash Lawrence', occupation: 'Developer' },
 { name: 'Jim Powers', occupation: 'Project Manager}]

I want to create an object that stores the unique counts of the different types of occupations, like so

{ developerCount: 3, qaTesterCount: 1, projectManagerCount: 1 }

My current solution is this long and drawn out method

let occupationCounts = {
  developerCount: 0,
  qaTesterCount: 0,
  projectManagerCount: 0
}

// Loop through the array and count the properties
users.forEach((user) => {
  switch(user.occupation){
    case 'Developer':
      occupationCounts.developerCount++;
      break;
      // and so on for each occupation
  }
}); 

This method will only grow for every new type of occupation I have to add.

Is there a simpler solution to this? (Pure javascript or Lodash Wizardry)

Any input is appreciated!

1 Answer 1

5

Array.prototype.reduce should help here, so long as you're not wedded to the specific count names:

const users = [
 { name: 'Bob Johnson', occupation: 'Developer' },
 { name: 'Joe Davidson', occupation: 'QA Tester' },
 { name: 'Kat Matthews', occupation: 'Developer' },
 { name: 'Ash Lawrence', occupation: 'Developer' },
 { name: 'Jim Powers', occupation: 'Project Manager'}
]

const counts = users.reduce((counts, {occupation}) => {
  counts[occupation] = (counts[occupation] || 0) + 1;
  return counts
}, {})

console.log(counts)

While you could do something to alter those names, I wouldn't bother unless it really matters.

Edit

If you do really want those, you can get close with something like this:

const key = occupation[0].toLowerCase() +
            occupation.slice(1).replace(/\s/g, '') + 'Count'
counts[key] = (counts[key] || 0) + 1;

But even that generates "qATesterCount" instead of "qaTesterCount". Going further would be a real challenge to do generically.

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

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.