DEV Community

Cover image for Sales by Match (HackerRank Javascript Solution)
Ibukun Demehin
Ibukun Demehin

Posted on

Sales by Match (HackerRank Javascript Solution)

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

Example

n = 7
ar = [1, 2, 1, 2, 1, 3, 2]
There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is.

Function Description

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

  • int n: the number of socks in the pile
  • int ar[n]: the colors of each sock

Returns

  • int: the number of pairs

Input Format

The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.

function sockMerchant(n, ar) {
    // Write your code here
    const uniqueValues = [... new Set(ar)]
    let count = 0
    uniqueValues.forEach(value => {
        const filterValues = ar.filter(element => element == value)
        const pairsNumber = Math.floor(filterValues.length/2)
        count += pairsNumber
    })
    return count
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)