Home > Blockchain >  Perform different actions in top 3 values in Dictionary?
Perform different actions in top 3 values in Dictionary?

Time:12-10

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..

CodePudding user response:

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

  • Related