

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' } ]
- Related Questions & Answers
- Get key from value in JavaScript
- Get MongoDB documents with max attribute per group in a collection?
- Top n max value from array of object JavaScript
- Get the max n values from an array in 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?
- Get key from value in Dictionary in Python
- Find Max Slice Of Array | JavaScript
- Java Program to generate random number array within a range and get min and max value
- Extract key value from a nested object in JavaScript?
- Converting miles per gallon to kilometer per liter in JavaScript
- Check if a value exists in an array and get the next value JavaScript
- Get the value associated with a given key in Java HashMap
Advertisements