Search code examples
javascriptarraysobjectoperatorslogical-operators

Count the Occurance of array elements Using Logical Operators with javascript and store it in a object with array items as key and frequency as value


for example, given the input array

const scored= ['Lewandowski'1, 'Gnarby'1, 'Lewandowski', 'Hummels'];

we should get output as

{Lewandowski: 2, Gnarby: 1, Hummels: 1}

And this should be done with help of logical operators only.


Solution

  • let us consider the array

    const scored= ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];
    

    Then we have to create a emtpty object

    const scorers={};
    

    Now looping through the array we can do

    for (const player of scored) {
      (scorers[player] += 1) || (scorers[player] === 1 || (scorers[player] = 1));
    }
    

    (scorers[player] += 1):-> First we try to add pretending that the "player" is there in object.if the player is there one will be added else if "player" is not there it will return Nan and continue with next expression (scorers[player] === 1 || (scorers[player] = 1)).Then we check for following steps.

    scorers[player] === 1:-> Next if the player is there,we check if value is 1 and if it has a value 1,the operation does not continue further.if player has a value 1,means that he has already been assigned a start value.

    scorers[player] = 1:-> The player does not have a value of 1,we assign him a value of 1 to start with.

    Below is what final code looks like

     const scored = ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];
    const scorers = {};
    for (const player of scored) {
       (scorers[player] += 1) || (scorers[player] === 1||(scorers[player]=1));
        }
    console.log(scorers);