
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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