Get 200+ icons, free for personal use: lovelicons.com

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%']