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

422
Views
Perform different actions in top 3 values in Dictionary?

I have a sorted dictionary with certain number of entries:

dict = {B:3, A:2, C:2, D:1, E:0, F:0...}

After filtering the dictionary to get only the entries with top 3 largest values:

result = Object.fromEntries(Object
    .entries(dict)
    .sort(([, a], [, b]) => b - a)                         
    .filter((s => ([, v]) => s.add(v).size <= 3)(new Set))
);

The current dictionary is

{"B": 3, "A": 2, "C": 2, "D": 1}

So I am trying to add 4 to the largest values,2 to the second largest values and 1 to the third largest values, what are the ways to do this?

The expected output: {"B": 7, "A": 4, "C": 4, "D": 2}

One of the ways I can think of is:

for (const key of Object.keys(result)) {
     // if result[key] largest
            //plus 4
     // if result[key] second largest
            //plus 2
     // else
            //plus 1 
}

Thanks for reading..

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You can do this using Map and flatMap as:

const dict = { B: 3, A: 2, C: 2, D: 1, E: 0, F: 0 };
const valuesToAdd = [4, 2, 1];
const result = Object.fromEntries([
    ...Object.entries(dict)
      .sort(([, a], [, b]) => b - a)
      .filter( ( (s) => ([, v]) => s.add(v).size <= 3 )(new Set()) )
      .reduce((map, arr) => {
        const [k, v] = arr;
        map.has(v) ? map.get(v).push(arr) : map.set(v, [arr]);
        return map;
      }, new Map())
      .values(),
  ].flatMap((arr, i) => arr.map(([k, v]) => [k, v + valuesToAdd[i]]))
);

console.log(result);

about 4 years ago · Santiago Gelvez 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!