Get max value per key in a JavaScript array



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' }
]

Advertisements