Search code examples
javascriptstatisticscurve

Compact range of data


If I have this array:

[ 0.8, 2, 3.33, 60, 98.6 ]

What kind of function (in JavaScript) can I write to make the values closer together, but on a scale? So that the smallest vals are still the smallest and the largest are still the largest, they are just closer?

Basically each of these vals is the radius of a bubble on a chart and I can barely see the small ones.. I want to make the small ones bigger and the big ones smaller proportionally.


Solution

  • It looks like you're trying to make every value closer to the average. Use a combination of Array#map and Array#reduce like this:

    var array = [ 0.8, 2, 3.33, 60, 98.6 ]
    var average = array.reduce(function (a, b) {
        return a + b
    }) / array.length
    var result = array.map(function (x) {
        return (x - average) / 2 + average
    }) //=> [16.873, 17.473, 18.138, 46.473, 65.773 ]
    

    Basically, this code calculates the average of your array, and then maps each value so that it is half the distance to that average.