Find n highest values in an object JavaScript


Let’s say, we have an object that describes various qualities of a football player like this −

const qualities = {
   defence: 82,
   attack: 92,
   heading: 91,
   pace: 96,
   dribbling: 88,
   tenacity: 97,
   vision: 91,
   passing: 95,
   shooting: 90
};

We wish to write a function that takes in such object and a number n (n <= no. of keys in object) and returns an object with n highest key value pairs.

Like for n = 2

Output should be −

{
   tenacity: 97,
   pace: 96
}

Therefore, let’s write the code for this function,

The complete code for this function will be −

Example

const qualities = {
   defence: 82,
   attack: 92,
   heading: 91,
   pace: 96,
   dribbling: 88,
   tenacity: 97,
   vision: 91,
   passing: 95,
   shooting: 90
};
const pickHighest = (obj, num = 1) => {
   const requiredObj = {};
   if(num > Object.keys(obj).length){
      return false;
   };
   Object.keys(obj).sort((a, b) => obj[b] - obj[a]).forEach((key, ind) =>
   {
      if(ind < num){
         requiredObj[key] = obj[key];
      }
   });
   return requiredObj;
};
console.log(pickHighest(qualities, 3));

Output

The output in the console will be −

{ tenacity: 97, pace: 96, passing: 95 }
{ tenacity: 97 }
{ tenacity: 97, pace: 96, passing: 95, attack: 92, heading: 91 }

Updated on: 20-Aug-2020

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements