Finding Max/Min values of an array using Spread Operator

Let's look at a the following array:

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

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
1
2
3
4

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
1
2
3
4
5

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 }
]
1
2
3
4
5
6
7

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)
1
2
3
4
5
6
7

¡And Voilà!

Join The Conversation