sockMerchant.js

    0

    1

    This code creates a function which will take an input of number "n" and return the number of pairs of socks a person has. The sockMerchant function will loop through the array of socks and keep track of how many pairs of socks each sock element has. If the sock element has a value of 1, then the sockMerchant function will add 1 to the value of the socks[element] variable. The function will also keep track of how many pairs of socks there are. If the value of the socks[element] variable is equal to 2, then the function will increment the number of pairs by 1.

    function sockMerchant(n, ar) {
      let socks = {};
      let pairs = 0;
    for (let element of ar) {
      socks[element] = socks[element] + 1 || 1;
        if (socks[element] % 2 === 0) {
          pairs += 1;
        }
      }
    return pairs;
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.