How to get the Max id in an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 08 20212 min read

banner

Photo by Tim Foster

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. The Math.max method returns the largest of the given numbers.
index.js
// Not Supported in IE 6-11 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.

In the code snippet we use the Array.map method to get an array containing the ids of all objects.

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

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

index.js
const max = Math.max(1, 7, 3, 14) console.log(max) // ๐Ÿ‘‰๏ธ 14

To get around this we use the Spread operator to unpack the values of the array.

The spread operator ... is not supported by Internet Explorer. If you need to support the browser use the approach using the apply method covered in this article.

If you need to support Internet Explorer, 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. The Math.max method returns the largest of the given numbers.
index.js
// Supported in IE 6-11 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 use the Function.apply method.

We pass 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, however if you have to support Internet Explorer, it gets the job done.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee