Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda