#4 - Pair of gloves CodeWars Kata (6 kyu)

cesar__dlr

Cesar Del rio

Posted on January 2, 2022

#4 - Pair of gloves CodeWars Kata (6 kyu)

Instructions:
Winter is coming, you must prepare your ski holidays. The objective of this kata is to determine the number of pair of gloves you can constitute from the gloves you have in your drawer.

Given an array describing the color of each glove, return the number of pairs you can constitute, assuming that only gloves of the same color can form pairs.

Example

input = ["red", "green", "red", "blue", "blue"]
result = 2 (1 red pair + 1 blue pair)

input = ["red", "red", "red", "red", "red", "red"]
result = 3 (3 red pairs)

My solution:

function numberOfPairs(gloves){

  var glovesObj = gloves.reduce((acc, el)=> {
    acc[el] = (acc[el] || 0) + 1;
    return acc;
  }, {})

  let r = 0;

  for(color in glovesObj){
    r+=Math.floor(glovesObj[color] / 2)
  }

  return r
}

Enter fullscreen mode Exit fullscreen mode

Explanation
I started using reduce on the gloves array, with this reduce function I could convert the array into an object that contains the color of the glove and how many times it is repeated this object looks like this:

input = ["red", "green", "red", "blue", "blue"]
Object = {"red": 2, "green": 1, "blue": 2}

Then I iterated this object using the For In loop, with this loop I could check every glove color and get how many pairs of gloves could I make with this color with the division that took the number of gloves of that color and divided it by 2, and then I used Math.floor so I get the result without the remainder, then I added this result to the r accumulator and at the end of the For In loop, I returned r

My Github
My twitter
Solve this Kata

💖 💪 🙅 🚩
cesar__dlr
Cesar Del rio

Posted on January 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

#4 - Pair of gloves CodeWars Kata (6 kyu)