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

90
Vistas
Count all values in object where X is the first key letter

I would like to count all values where a letter appears first and return the letter with atleast half of all values in my object so for example I assuming I have an object like this

const sample = { "A,B,C": 4, "B,C,A": 3, "C,B,A": 2, "A,C,B": 2 };

I would return A because if you count all the values where A appears first you would get 6 (4+2)

This is what I currently have:

for (let votes of Object.values(sample)) {
  sum += votes
}
stretchWin = Math.round(sum / 2)
winner = Object.entries(sample)
  .filter(([, val]) => val >= stretchWin)
  .map(([keys]) => keys)

With this I am getting an empty array because I am not counting all the values assigned to A

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

0

Iterate over the whole sample first to get a sum of the values by the first letter first, then iterate over that new object to identify which values match the target of half the total.

const sample = {
  "A,B,C": 4,
  "B,C,A": 3,
  "C,B,A": 2,
  "A,C,B": 2
};
const sumByChar = {};
for (const [key, value] of Object.entries(sample)) {
  const char = key[0];
  sumByChar[char] = (sumByChar[char] ?? 0) + value;
}
let sum = 0;
for (let votes of Object.values(sample)) {
  sum += votes
}
const targetSum = Math.round(sum / 2);
const winners = Object.entries(sumByChar)
  .filter(([, val]) => val >= targetSum)
  .map(([key]) => key);
console.log(winners);

about 4 years ago · Juan Pablo Isaza Denunciar

0

I'm not completely sure what you mean what the outcome should be. If I understand correctly you want something like this??

const sample = { "A,B,C": 4, "B,C,A": 3, "C,B,A": 2, "A,C,B": 2 };
const totalSum = Object.values(sample).reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  0
);
const stretchWin = Math.round(totalSum / 2);

const winner = Object.entries(sample)
  .filter(([key, value]) => {
    const isFirstLetterA = key.startsWith("A");
    return isFirstLetterA || value >= stretchWin;
  })
  .map(([key, value]) => value)
  .reduce((previousValue, currentValue) => previousValue + currentValue, 0);

console.log(winner);

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