twitch
Streaming on Twitch twice a week

Removing the largest number from an array

JavaScript

We can remove all instances of the largest number in an array by combining Math.max() and Array.prototype.filter().

We first need to know which number we have to remove. Since we cannot rely on the array being sorted, we have to use Math.max() to find that number.

const max = Math.max(16, 4, 23, 15, 42, 8)
// ⇒ 42

Math.max() accepts an unspecified number of parameters instead of a single array. To pass an array to it, we need to spread it using the spread operator ....

const numbers = [16, 4, 23, 15, 42, 8]
const max = Math.max(...numbers)
// ⇒ 42

Once we know the largest number, we can use Array.prototype.filter() to filter that value from the array. We get a copy of the original array with only the numbers that are not the largest value.

const numbers = [16, 4, 23, 15, 42, 8]
const max = Math.max(...numbers)
numbers.filter(number => number !== max)
// ⇒ [16, 4, 23, 15, 8]

By putting this logic in a helper function, we can quickly remove the largest value from any number of arrays.

// removes the largest value from an array of numbers
function removeMax(numbers) {
  // get this first so we only need to calculate it once
  const max = Math.max(...numbers)

  // create a new array from all numbers that are NOT `max`
  return numbers.filter(number => number !== max)
}

We can use this function to remove the largest number from any numerical array in a single line. If the largest value appears more than once, all instances are removed.

// remove the largest number from our example
removeMax([16, 4, 23, 15, 42, 8])
// ⇒ [16, 4, 23, 15, 8]

// it removes multiple instances of the same largest number
removeMax([12, 27, 8, 9, 41, 33, 41, 29])
// ⇒ [12, 27, 8, 9, 33, 29]

// if all numbers are the maximum, it returns an empty array
removeMax([5, 5, 5, 5, 5, 5, 5])
// ⇒ []

// it works with negative numbers as well
removeMax([-5, -2, -8, -1, -10])
// ⇒ [-5, -2, -8, -10]