Get the Max id in an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the Max id in an Array of Objects #

To get the max id in an array of objects:

  1. Get an array of ids, using the map() method.
  2. Call the Math.max method, passing it the array of ids, prefixed by the spread operator as a parameter.
  3. The Math.max method returns the largest of the given numbers.
index.js
const arr = [{id: 1}, {id: 7}, {id: 3}, {id: 14}]; const ids = arr.map(object => { return object.id; }); console.log(ids); // 👉️ [1, 7, 3, 14] const max = Math.max(...ids); console.log(max); // 👉️ 14
If you also need the min object id, call the Math.min method with the same argument.

We used the Array.map method to get an array containing the ids of all objects.

index.js
const arr = [{id: 1}, {id: 7}, {id: 3}, {id: 14}]; const ids = arr.map(object => { return object.id; }); console.log(ids); // 👉️ [1, 7, 3, 14]

We then called the Math.max method using the spread operator.

The Math.max method expects comma-separated numbers as parameters, so we can't directly pass it an array.

index.js
const max = Math.max(1, 7, 3, 14) console.log(max) // 👉️ 14

We used the Spread operator to unpack the values of the array in the call to Math.max.

index.js
const arr = [{id: 1}, {id: 7}, {id: 3}, {id: 14}]; const ids = arr.map(object => { return object.id; }); console.log(ids); // 👉️ [1, 7, 3, 14] const max = Math.max(...ids); console.log(max); // 👉️ 14

Alternatively, you can use the Function.apply method instead of the spread operator.

To get the max id in an array of objects:

  1. Get an array of ids, using the map() method.
  2. Call the apply method on Math.max, passing it null and the array of ids as parameters.
  3. The Math.max method returns the largest of the given numbers.
index.js
const arr = [{id: 1}, {id: 7}, {id: 3}, {id: 14}]; const ids = arr.map(object => { return object.id; }); console.log(ids); // 👉️ [1, 7, 3, 14] const max = Math.max.apply(null, ids); console.log(max); // 👉️ 14

Instead of using the ... operator, we used the Function.apply method.

We passed the following 2 arguments to the method:

  1. the this argument - for our purposes it's irrelevant
  2. an array of numbers that the apply method will pass to Math.max as arguments
Under the hood, the apply method unpacks the values from the array and passes them as comma-separated arguments to the Math.max method.

This approach is less readable and intuitive than the first one and should only be used if you have to support older browsers.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.