I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Converting numerical arrays into relative fractions

Posted on

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

const toRelative = numbers => {
  const largestNumber = Math.max(...numbers)
 
  return numbers.map(number => number / largestNumber)
}
 
// The largest number in the array, 16, becomes 1 (= 100%) in the result. All
// other results are based on that: 8 is 0.5 (= 50%) of 16, 4 is 0.25 (= 25%),
// and so on.
toRelative([0, 8, 12, 6, 16, 3, 0])
// ⇒ [0, 0.5, 0.75, 0.375, 1, 0.1875, 0]
 
// Relative values are based on the largest value, which is 40 in this example.
toRelative([8, 15, 21, 5, 10, 40])
// ⇒ [0.2, 0.375, 0.525, 0.125, 0.25, 1]
const toRelative = numbers => {
  const largestNumber = Math.max(...numbers)
 
  return numbers.map(number => number / largestNumber)
}
 
// The largest number in the array, 16, becomes 1 (= 100%) in the result. All
// other results are based on that: 8 is 0.5 (= 50%) of 16, 4 is 0.25 (= 25%),
// and so on.
toRelative([0, 8, 12, 6, 16, 3, 0])
// ⇒ [0, 0.5, 0.75, 0.375, 1, 0.1875, 0]
 
// Relative values are based on the largest value, which is 40 in this example.
toRelative([8, 15, 21, 5, 10, 40])
// ⇒ [0.2, 0.375, 0.525, 0.125, 0.25, 1]
Debug
none
Grid overlay