JavaScript Program to find Number of Pairs in an Array

For the array:

const arr = [10, 20, 20, 10, 10, 30, 50, 10, 20];

we need to find how many pairs of matching numbers exist.

Expected Output

3

Explanation:

  • 10 appears 4 times → 2 pairs
  • 20 appears 3 times → 1 pair
  • 30 appears 1 time → 0 pairs
  • 50 appears 1 time → 0 pairs

Total pairs = 2 + 1 = 3


JavaScript Solution

const arr = [10, 20, 20, 10, 10, 30, 50, 10, 20];
function findPairs(numbers) {
const frequency = {};
for (const num of numbers) {
frequency[num] = (frequency[num] || 0) + 1;
}
console.log("Frequency:", frequency);
let pairs = 0;
for (const key in frequency) {
pairs += Math.floor(frequency[key] / 2);
}
return pairs;
}
console.log("Total Pairs:", findPairs(arr));

Discover more from Learners Store

Subscribe to get the latest posts sent to your email.

Leave a comment