'number of pairs from array by JS

following is my code to find number of pairs of duplicate values from the array given below.

ar = [1 1 3 1 2 1 3 3 3 3] answer for this array is 3. but expected output is 4. explanation: pairs in the given array are (1,1), (3,3), (1,1), (3,3) and so the number of pairs are 4(the expected output.

but the same code is giving right result for the following array.

ar = [10 20 20 10 10 30 50 10 20] answer for this array is 3 and expected output is also 3. explanation: in this array pairs are (10,10), (20,20), (10,10) and so the number of pairs are 3(the expected output).

function sockMerchant(n, ar) {
    let dups = 0;
    for (let i=0; i<ar.length; i++){
        for (let j=i+1; j<ar.length; j++){
            if (ar[i]==ar[j]){
                dups++;
            }
        }
        break;
    }
    return dups;
}


Solution 1:[1]

Your approach with nested iterations does not work, because you need to exclude the value of a found pair in the inner loop from being iterated again.

In this case, you need another data structure, like a Set or an object to exclude an index with the second value of a pair.

You still have the problem of a nesting iteration.

To overcome this problem, you could take a hash table and count the same value and if the count is 2 increment a total counter and reset the hash value.

function countPairs(array) {
    const pairs = {};
    
    let count = 0;
    
    for (const value of array) {
        pairs[value] = (pairs[value] || 0) + 1;
        if (pairs[value] === 2) {
            count++;
            pairs[value] = 0;
        }
    }
    
    return count;
}

console.log(countPairs([1, 1, 3, 1, 2, 1, 3, 3, 3, 3]));       // 4
console.log(countPairs([10, 20, 20, 10, 10, 30, 50, 10, 20])); // 3

Solution 2:[2]

Just another solution using Set:

function sockMerchant(socks) {
  let foundPairs = 0;
  const singleSocks = new Set();
  
  for (let sock of socks) {
    if (singleSocks.has(sock)) {
      singleSocks.delete(sock);
      foundPairs++;
    } else {
      singleSocks.add(sock);
    }
  }
  return foundPairs;
}

console.log(sockMerchant([1, 1, 3, 1, 2, 1, 3, 3, 3, 3]));       // 4
console.log(sockMerchant([10, 20, 20, 10, 10, 30, 50, 10, 20])); // 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 javoski