My current approach is not providing me with the desired result. I am facing an issue where pairs of 1 are being counted multiple times, which is incorrect. What I actually need is to count only the "perfect" pairs, such as the pair between 5 and 2 in this case. As of now, my solution is returning 4 when it should be 2.
I am struggling to find a way to achieve this. Any suggestions would be greatly appreciated.
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (ar) => {
let obj = {};
ar.forEach((item) => {
obj[item] = obj[item] ? obj[item] + 1 : 1;
});
return Object.values(obj).reduce((acc, curr) => {
acc += Math.floor(curr / 2);
return acc;
}, 0);
};
console.log( countPairs(ar1) )