Home > Software design >  how to get the number of pair values in array? Javascript
how to get the number of pair values in array? Javascript

Time:11-11

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) )
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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) )
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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) )
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related