How to get the min and max of an array in JavaScript

Published on

The simplest way to get the minimum or maximum values of an array is by using Math.max and Math.min methods. This can be done either by using apply or by spreading the array elements inside the method call. Despite what some solutions available on the internet suggest you do not need to pass Math as the first argument of apply.

const scores = [1, 8, 3, 7, 16];

const min = Math.min.apply(null, scores);
console.log(min);
// 1

const max = Math.max.apply(null, scores);
console.log(max);
//  16

const minSpread = Math.min(...scores);
console.log(minSpread);
// 1

const maxSpread = Math.max(...scores);
console.log(maxSpread);
//  16

If you're trying to find the max/min value for a certain property on an array of objects you can pair either of these methods with a map to drill down onto the specific property before you compute the max/min.

const players = [
  {
    name: 'Brian Bluff',
    score: 1,
  },
  {
    name: 'Anthony Smiff',
    score: 16,
  },
  {
    name: 'Keegan Campbell',
    score: 8,
  },
];

const min = Math.min.apply(
  null,
  players.map((s) => s.score)
);

console.log(min);
// 1

const max = Math.max.apply(
  null,
  players.map((s) => s.score)
);

console.log(max);
//  16

You could even adapt this code to make a utility method that would work for any array of objects as seen below. It is also null safe so will still work if the property does not exist on one of the objects in the array.

const players = [
  {
    name: 'Brian Bluff',
    score: 1,
  },
  {
    name: 'Anthony Smiff',
    score: 16,
  },
  {
    name: 'Keegan Campbell',
  },
  {
    name: 'Melanie Lucas',
    score: 10,
  },
];

const maxArrProperty = (array, property) => {
  return Math.max.apply(
    null,
    array.map((s) => s?.[property] ?? -Infinity)
  );
};

const max = maxArrProperty(players, 'score');

console.log(max);
//  16