Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!