Explain Codes LogoExplain Codes Logo

Finding the max value of a property in an array of objects

javascript
functions
performance
best-practices
Alex KataevbyAlex Kataev·Dec 10, 2024
TLDR

To discover the maximum value of a property in an object array, integrate Math.max() with map():

const maxPropValue = Math.max(...array.map(obj => obj.property));

Substitute property with the specific key you're focusing on. This process creates a fresh array of values, from which Math.max() calculates the overall maximum.

Understanding the details

The empty array anomaly

Dealing with empty arrays often requires a specific approach. Math.max(), when dealing with an empty array, returns -Infinity. A smart workaround is to supply a default value:

const maxPropValue = array.length === 0 ? defaultValue : Math.max(...array.map(obj => obj.property));

The defaultValue here could be 0, null, or any value that fits your specific solution.

Performance conundrum: Large arrays

For huge arrays, using the spread operator can force the call stack limit to its knees. Instead, employ the reduce() method:

const maxPropValue = array.reduce((max, obj) => Math.max(max, obj.property), -Infinity);

This approach proves more good-natured towards memory, avoids call stack limit issues and manages large datasets with aplomb.

Adapting modern ES6 syntax

Adopt arrow functions and the spread operator to write sleek, modern JavaScript:

const maxPropValue = Math.max(...array.map(obj => obj.property));

In one stroke, this code combines readability and succinctness, calling on the power of current JavaScript features.

Practical cases

Below are several real-world situations and techniques that can elevate your coding when working with max value extraction.

Sorting as a tool

Sorting can be a part of your toolkit. Check out:

// Let's try the shell game with array elements! array.sort((a, b) => b.property - a.property); const maxPropValue = array[0].property;

Remember, array.sort() loves to shake up the original array and operates with the time complexity of O(n log n).

Possible snags and solutions

  • Large array? reduce() to the rescue.
  • Empty array? Get ahead, set a default value.
  • Readability or performance? Prioritize according to array size and operational frequency.

Code testing - A non-negotiable

While our techniques are compatible pretty much everywhere, always ensure compatibility in every environment where your code gets deployed, especially if you're using newer ES6 features.