Home > Software design >  Find top 3 values entries in a sorted JavaScript dictionary?
Find top 3 values entries in a sorted JavaScript 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...}

Are there any ways to filter the dictionary to find the entries with top 3 largest values while considering duplicated values so the output will be? :

output = {B:3, A:2, C:2, D:1}

Thanks for reading..

CodePudding user response:

You could count distinct values with a Set and filter ordered entries for getting an object from it.

const
    object = { B: 3, A: 2, C: 2, D: 1, E: 0, F: 0 },
    result = Object.fromEntries(Object
        .entries(object)
        .sort(([, a], [, b]) => b - a)                         // just to be sure
        .filter((s => ([, v]) => s.add(v).size <= 3)(new Set))
    );
    
console.log(result);

CodePudding user response:

Maybe this can help you.

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

// Create items array
var items = Object.keys(dict).map(function(key) {
  return [key, dict[key]];
});

// Sort the array based on the second element
items.sort(function(first, second) {
  return second[1] - first[1];
});

// Create a new array with only the first 3 items
let slicedArray = items.slice(0, 3);

//Return appropriate value
let dictSorted = slicedArray.reduce((a, x) => ({ ...a,
  [x[0]]: x[1]
}), {});
console.log(dictSorted);

  • Related