Converting numerical arrays into relative fractions

We needed to convert an array of (positive) numbers into fractions of each other, with the largest number being 100 percent. This function turns all values into percentages between 0 and that largest value.

const toPercentages = numbers => {
  const largestNumber = Math.max(...numbers)

  return numbers.map(number => `${number / largestNumber * 100}%`)
}

// Because 16 is the largest number in the array, it is treated as 100%. All
// other values are based on that: 8 is 50% of 16, 4 is 25%, and so on.
toPercentages([0, 8, 12, 6, 16, 3, 0])
// ⇒ ['0%', '50%', '75%', '37.5%', '100%', '18.75%', '0%']

// Percentages are based on the largest value, which is 40 in this example.
toPercentages([8, 15, 21, 5, 10, 40])
// ⇒ ['20%', '37.5%', '52.5%', '12.5%', '25%', '100%']

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.