Get max value per key in a JavaScript array

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

const arr = [
   {a:1, b:"apples"},
   {a:3, b:"apples"},
   {a:4, b:"apples"},
   {a:1, b:"bananas"},
   {a:3, b:"bananas"},
   {a:5, b:"bananas"},
   {a:6, b:"bananas"},
   {a:3, b:"oranges"},
   {a:5, b:"oranges"},
   {a:6, b:"oranges"},
   {a:10, b:"oranges"}
];

We are required to write a JavaScript function that takes in one such array and returns an array of objects.

The array should contain an object for each unique value of "b" property where the "a" property has the highest value.

The code for this will be −

const arr = [
   {a:1, b:"apples"},
   {a:3, b:"apples"},
   {a:4, b:"apples"},
   {a:1, b:"bananas"},
   {a:3, b:"bananas"},
   {a:5, b:"bananas"},
   {a:6, b:"bananas"},
   {a:3, b:"oranges"},
   {a:5, b:"oranges"},
   {a:6, b:"oranges"},
   {a:10, b:"oranges"}
];

const pickHighest = arr => {
   const res = [], map = {};

   arr.forEach(el => {
      if (!(el['b'] in map)) {
         map[el['b']] = res.push(el) - 1;
         return;
      };
      if(res[map[el['b']]]['a'] < el['a']){
         res[map[el['b']]] = el;
      };
   });
   return res;
};
console.log(pickHighest(arr));

Following is the output on console −

[
   { a: 4, b: 'apples' },
   { a: 6, b: 'bananas' },
   { a: 10, b: 'oranges' }
]
raja
Published on 09-Oct-2020 11:11:26
Advertisements