Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an object called 'scorers' which contains the names of the players who scored as properties

so i’ve been working on problem and i found the solution but I would like please someone to explain me further why this works actually

const game = {
    team1: 'Bayern Munich',
    team2: 'Borrussia Dortmund',
    score: '4:0',
    scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'],
    date: 'Nov 9th, 2037',
    odds: {
      team1: 1.33,
      x: 3.25,
      team2: 6.5,
    },
  };

So, having the above object I was trying to : create an object called ‘scorers’ which contains the names of the
players who scored as properties, and the number of goals as the value. In this
game.
I came with this solution :

const scorers = {};
for (const player of game.scored) {
  scorers[player] ? scorers[player]++ : (scorers[player] = 1);
};
console.log(scorers);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You start by creating a new empty object, then iterate over all the players that are in the game.scored array. What the next line (conditional operator or ternary) does is the following:

if (scorers[player])
    scorers[player]++;
else
    scorers[player] = 1;

Ternary operators work as follows: <condition> ? <return if true> : <return if false>. You can also chain ternary operators: <condition1> ? <return if true> : (<condition2> ? <return if true> : <return if false>)

In the "if" condition, if you pass only a variable, it compares it with true. Basically its if (scorers[player]===true), which checks if the player key exists in the object scorers. If it does, then it increments its score by 1, if not, it creates it with value 1.

Hope you could understand from my brief explanation!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading