How to create scales between min and max value using ranges in javascript?
arrays, function, javascript, object
Solution
Have a look at this:
function getScales(minRange, maxRange, min, max){
var scales = [], // Prepare some variables
ranges = maxRange+1 - minRange, // Amount of elements to be returned.
range = (max-min)/ranges; // Difference between min and max
for(var i = 0; i < ranges; i++){
scales.push({
range: i+minRange, // Current range number
min: min + range * i,
max: min + range * (i+1)
});
}
return scales;
}
You can call the function like this:
getScales(0, 9, 0, 1000);
Output:
[
{
"range": 0,
"min": 0,
"max": 100
},
{
"range": 1,
"min": 100,
"max": 200
},
.......
{
"range": 8,
"min": 800,
"max": 900
},
{
"range": 9,
"min": 900,
"max": 1000
}
]
To get rid of the floating point errors in the output, you can replace:
min: range * i,
max: range * (i+1)
With:
min: (range * i).toFixed(2),
max: (range * (i+1)).toFixed(2)
Replace the `2` with the desired amount of digits behind the decimal point.
Problem
I need to create a dynamic scales something like this ``` Range 1 = 0 to 100 Range 2 = 100 to 200 Range 3 = 200 to 300 Range 4 = 300 to 400 Range 5 = 400 to 500 Range 6 = 600 to 700 Range 7 = 700 to 800 Range 8 = 800 to 900 Range 9 = 900 to 1000 ``` Here, ranges are 1 to 9 and minimum value is 0 and maximum value is 1000. These ranges, minimum and maximum values are dynamic. So, I required a function to return the scales. For example:- ``` function getScales(minRage, maxRange, minValue, maxValue){ var scales={}; .......... ............ return scales; } //Output: [ { range :1 min :0, max :100 }, { range :2 min :100, max :200 }, { range :3 min :200, max :300 }, .... .... { range :9, min :900, max :1000 } ] ``` To get above result , I need to call the function like this `getScales(1, 9, 0, 1000)`. This is what my actual requirement: if I call `getScales(1, 5, 4000, 418500)`;