Finding Max/Min values of an array using Spread Operator

Last Updated On 30 Jan 2020 by

Let’s look at a the following array:

const values = [12, 9, 24, 1, -23, 5, 99, 5, -2, 43];

We could loop over the array and saving the max value if it is greater than the one previously saved, then do the same with the min value, if it’s lower than the one previously saved. But we might as well rely on the built in Math API of JavaScript.

Before we reveal the trick, it’s important you understand how Math.min and Math.max work. These functions can accept as many parameters as you need and will calculate the min/max value over all of them.

For example:

Math.min(12, 9, 24, 1, -23, 5, 99, 5, -2, 43);
// output: -23
Math.max(12, 9, 24, 1, -23, 5, 99, 5, -2, 43);
// output: 99

The Spread Operator

However, we’re trying to do it programmatically - with a variable instead of hard coded values. That’s where the so called spread operator or ... comes in handy:

const values = [12, 9, 24, 1, -23, 5, 99, 5, -2, 43];
Math.min(...values);
// output: -23
Math.max(...values);
// output: 99

Taking it a step further

Now let’s look at this more complex array:

const people = [
  { name: "Pantxica", age: 32 },
  { name: "Ramon", age: 18 },
  { name: "Tintuline", age: 41 },
  { name: "Iñaki", age: 27 },
  { name: "Eneko", age: 114 },
];

In order to find the youngest and oldest person in the set, we can use Array.map:

const ages = people.map((person) => person.age);
const min = Math.min(...ages); // output: 18
const max = Math.max(...ages); // output: 114
console.log(
  `The oldest person: ${people[ages.indexOf(max)].name} (${max} years old)`
);
// output: The oldest person: Eneko (114 years old)
console.log(
  `The youngest person: ${people[ages.indexOf(min)].name} (${min} years old)`
);
// output: The youngest person: Ramon (18 years old)

¡And Voilà!

About The Author

Headshot of Michael Iriarte aka Mika

Hi, I'm Michael aka Mika. I'm a software engineer with years of experience in frontend development. Thank you for visiting tips4devs.com I hope you learned something fun today! You can follow me on Twitter, see some of my work on GitHub, or read more about me on my website.