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

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:

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

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

>Solution :

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