dannuzak
dannuzak

Reputation: 109

how to get the number of pair values in array? Javascript

I am trying this solution but it is not giving me the result I want. I don't want to count the number of pairs of 1 cause it is not really a pair as it appears 4 times. I need to count the "perfect" pairs, like in this case: 5 and 2. Right now this is giving me 4 as result and it should be 2.

How could I achieve that? I am stuck.

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) )

Upvotes: 1

Views: 1086

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22335

or that

const 
  ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val,i,{[i+1]:next})=>
    {
    if(!r.counts[val])
      { 
      r.counts[val] = arr.filter(x=>x===val).length
      if (r.counts[val]===2) r.pairs++
      }
    return  next ? r : r.pairs
    },{counts:{},pairs:0}) 


console.log( countPerfectPairs(ar1) )

If you prefer Details:

const 
  ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val)=>
    {
    if(!r.counts[val])
      { 
      r.counts[val] = arr.filter(x=>x===val).length
      if (r.counts[val]===2) r.pairs++
      }
    return r
    },{counts:{},pairs:0}) 


console.log( countPerfectPairs(ar1) )

Upvotes: 0

DecPK
DecPK

Reputation: 25408

This can be one-liner using Map as:

const countPairs(arr)  => [...arr.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map()).values(),].filter((n) => n === 2).length;

let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];

const countPairs = (arr) =>
  [
    ...arr
      .reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map())
      .values(),
  ].filter((n) => n === 2).length;

console.log(countPairs(ar1));

Upvotes: 1

Sopheak Sek
Sopheak Sek

Reputation: 162

You can filter the object values by 2 and count the list

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).filter(e => e == 2).length;
};

console.log(countPairs(ar1))

Upvotes: 3

Related Questions