Alexander
Alexander

Reputation: 1378

Trying to do a counter object in javascript

I'm trying to do a counter object in JavaScript like so: EDIT: I've added an example

    let profile={skill:['javascript','javascript','html','css','css']}
    let objectCount={}

profiles.map(profile => {
        profile.skills.map(skill => {
          skill = skill.toLowerCase();
          if (!(skill in objectCount)) {
            objectCount = { ...objectCount, [skill]: 1 };
          } else {
            objectCount.skill = objectCount.skill + 1;
          }
        });
      });
    }

I have array of profiles and inside them an array of skills which is : 'javascript','html','css',etc and I wish to make an objectCount that will be:

objectCount={
  'html':1,
  'javascript:2,
   'css':2
}

but for some reason the line objectCount.skill=objectCount.skill+1 doesnt work, because I get an object with 1 in every single key, does anybody know whats my error?

Upvotes: 2

Views: 2571

Answers (2)

Joyce Lee
Joyce Lee

Reputation: 386

Another way of creating this counter map is to use the reduce function instead of map.

For example: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#counting_instances_of_values_in_an_object

Upvotes: 0

Sarah Groß
Sarah Groß

Reputation: 10879

You're trying to increment the value of a key skill on the objectCount object that does not exist. Instead you want to increment the value of the key that has the name of the skill variable. So you have to use objectCount[skill] instead of objectCount.skill:

let profiles = [
  {
    skills: ['html', 'js']
  },
  {
    skills: ['html', 'php']
  }
]
let objectCount = {}

profiles.map(profile => {
  profile.skills.map(skill => {
    skill = skill.toLowerCase();
    if (!(skill in objectCount)) {
      objectCount = { ...objectCount, [skill]: 1 };
    } else {
      objectCount[skill] = objectCount[skill] + 1;
    }
  });
});
console.log(objectCount);

Upvotes: 4

Related Questions