Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
Count pairs of elements in array and sum it up

I want to create a function that counts pairs of an array and at the end count up the pairs, the expected result here should be:

{
  1: 1,
  10: 1,
  90: 2
}, 4

But I am getting

{
  1: 1,
  90: 2
}, 3

Can someone give piece of advice how to rework this? It is not getting 10 as a pair because it occurs three times, but it should count it as a pair because it was up twice. Are there better methods to create this?

const pairs = [90, 10, 1, 2, 3, 4, 5, 10, 1, 90, 90, 90, 10, 22];

function checkPairs(arr) {
    const result = {}
    for(let i =0;i<pairs.length;i++) {
      const counter = pairs.filter(item => item == arr[i]);
      if(counter.length > 1 && counter.length % 2 == 0) {
        result[pairs[i]] = counter.length/2;
     }
}
    return result;
}

function countPairs(obj) {
    let result = 0;
    for([i, t] of Object.entries(obj)) {
    result+=t;
  }
  return result;
}

const countedPairs = checkPairs(pairs);
const counter = countPairs(countedPairs);


console.log(countedPairs, counter)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your check is saying there has to be exact number for pairs when you are doing counter.length % 2 == 0

You just need to make sure you have 2 or more and just round down with floor

const pairs = [90, 10, 1, 2, 3, 4, 5, 10, 1, 90, 90, 90, 10, 22];

function checkPairs(arr) {
    const result = {}
    for(let i =0;i<pairs.length;i++) {
      const counter = pairs.filter(item => item == arr[i]);

      if(counter.length > 1) {
        result[pairs[i]] = Math.floor(counter.length/2);
     }
}
    return result;
}

function countPairs(obj) {
    let result = 0;
    for([i, t] of Object.entries(obj)) {
    result+=t;
  }
  return result;
}

const countedPairs = checkPairs(pairs);
const counter = countPairs(countedPairs);


console.log(countedPairs, counter)

Your filter code causes you to loop way more than you need to. You just have to loop once over the array and keep track of the times you have seen it.

const pairs = [90, 10, 1, 2, 3, 4, 5, 10, 1, 90, 90, 90, 10, 22];

const counts = pairs.reduce(function (o, val) {
  // update how many times we have seen it. 
  o.count[val] = (o.count[val] || 0) + 1;
  // is it the a pair yet?
  if (o.count[val] ===2) {
    // if it is, reset the count
    o.count[val] = 0;
    // update the count for the pair
    o.pairsCount[val] = (o.pairsCount[val] || 0) + 1;
    o.totalPairs++;
  }
  return o;
}, { count: {}, pairsCount: {}, totalPairs: 0});

console.log(counts.pairsCount, counts.totalPairs);

about 4 years ago · Juan Pablo Isaza Denunciar

0

How about you try this approach? Checking the length of counter array is even. If yes then do the regular calculation else just subtract 1 from counter's length.

const pairs = [90, 10, 1, 2, 3, 4, 5, 10, 1, 90, 90, 90, 10, 22];

function checkPairs(arr) {
    const result = {}
    for(let i =0;i<pairs.length;i++) {
      const counter = pairs.filter(item => item == arr[i]);
      if(counter.length > 1) {
        result[pairs[i]] = counter.length % 2 == 0 ? counter.length / 2 : (counter.length -1) / 2 ;
     }
}
    return result;
}

function countPairs(obj) {
    let result = 0;
    for([i, t] of Object.entries(obj)) {
    result+=t;
  }
  return result;
}

const countedPairs = checkPairs(pairs);
const counter = countPairs(countedPairs);


console.log(countedPairs, counter)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can also do it using Array.prototype.reduce.

  1. For every number increment it's count by 1.
  2. Whenever the count for a particular number becomes even, increment the total by 1.

const 
  nums = [90, 10, 1, 2, 3, 4, 5, 10, 1, 90, 90, 90, 10, 22],
  totalPairs = nums.reduce(
    (acc, num) => {
      acc[num] ??= 0;
      acc[num] += 1;
      if (!(acc[num] % 2)) {
        acc.total += 1;
      }
      return acc;
    },
    { total: 0 }
  ).total;

console.log(totalPairs);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda