Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading