- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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' } ]
- Related Articles
- Get key from value in JavaScript
- Get the max n values from an array in JavaScript
- Get MongoDB documents with max attribute per group in a collection?
- Top n max value from array of object JavaScript
- JavaScript - Convert an array to key value pair
- Get value for key from nested JSON object in JavaScript
- Find specific key value in array of objects using JavaScript
- Creating a JavaScript Object from Single Array and Defining the Key Value?
- Java Program to generate random number array within a range and get min and max value
- Find Max Slice Of Array | JavaScript
- Check if a value exists in an array and get the next value JavaScript
- Appending a key value pair to an array of dictionary based on a condition in JavaScript?
- Get key from value in Dictionary in Python
- Extract key value from a nested object in JavaScript?
- Average of array excluding min max JavaScript

Advertisements