Search code examples
javascriptjsonscale

Javascript: Iterate through list of objects and scale the values between known min and max


I have a list of objects and I want to scale the values between a known min and max. So if the known min and max are 100, 800, I'd want the result to be as follows:

{'cat' : 1, 'dog' : 3, 'chimp' : 8} -> {'cat' : 100, 'dog' : 300, 'chimp' : 800}

The Python/pandas implementation looks like this

def scale_size(old_value):
        if numbers_df['raw_size'].max() == 1:
            return 150
        old_value = float(old_value)
        old_max = numbers_df['raw_size'].max()
        old_min = numbers_df['raw_size'].min()
        new_max = 150
        new_min = 20
        old_range = old_max - old_min
        new_range = new_max - new_min
        new_value =  (((old_value - old_min) * new_range) / old_range) + new_min

        return int(new_value)

Solution

  • You should create a function to map your values from one range to another. To do this, you should do the following:

    • Figure out the minimum and maximum of your current range (e.g. (1,8))
    • Figure out the minimum and maximum of the range to which you want to map the values (e.g. (100,800))
    • Map existing values from one range to another, by calculating the relative position in the old range and applying that relative position to the new range

    Sample code

    I'm sure there are more efficient and/or cleaner ways to achieve this, but this could be a decent starting point for what you want to do. On a side note, you could theoretically calculate the minimum and maximum of your current range by finding the smallest and largest values in your key-value pairs, however this might not be ideal for all cases.

    var oldVals = {'cat' : 1, 'dog' : 3, 'chimp' : 8};
    
    function mapValues(oldMin, oldMax, newMin, newMax, values){
      var newVals = {};
      for (key in values){
        newVals[key] = (values[key] - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin;
      }
      return newVals;
    }
    
    console.log(mapValues(1, 8, 100, 800, oldVals));