Get max value per key in a JavaScript array

When working with arrays of objects in JavaScript, you might need to find the object with the maximum value for a specific property within each group. This is a common task when analyzing data grouped by categories.

Consider this array of fruit data:

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"}
];

console.log(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 need to find the object with the highest "a" value for each unique "b" category.

Using forEach with Map Tracking

This approach uses a map to track the index of each group's current maximum:

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

[
  { a: 4, b: 'apples' },
  { a: 6, b: 'bananas' },
  { a: 10, b: 'oranges' }
]

Using reduce() Method

A more functional approach using reduce to build a Map:

const getMaxByKey = arr => {
    const maxMap = arr.reduce((acc, current) => {
        const key = current.b;
        if (!acc.has(key) || acc.get(key).a 

[
  { a: 4, b: 'apples' },
  { a: 6, b: 'bananas' },
  { a: 10, b: 'oranges' }
]

Using Object.values() with groupBy

Create groups first, then find the maximum in each group:

const findMaxPerGroup = arr => {
    const groups = {};
    
    // Group by 'b' property
    arr.forEach(item => {
        if (!groups[item.b]) {
            groups[item.b] = [];
        }
        groups[item.b].push(item);
    });
    
    // Find max 'a' in each group
    return Object.values(groups).map(group => 
        group.reduce((max, current) => 
            current.a > max.a ? current : max
        )
    );
};

console.log(findMaxPerGroup(arr));
[
  { a: 4, b: 'apples' },
  { a: 6, b: 'bananas' },
  { a: 10, b: 'oranges' }
]

Performance Comparison

Method Time Complexity Space Complexity Readability
forEach with Map O(n) O(k) Medium
reduce() with Map O(n) O(k) High
groupBy approach O(n) O(n) High

where n = array length, k = unique keys

Conclusion

All methods achieve the same result, but the reduce() with Map approach offers the best balance of performance and readability. Choose the forEach approach for maximum performance with large datasets, or the groupBy method when code clarity is the priority.

Updated on: 2026-03-15T23:19:00+05:30

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements