3

I am trying to create an array that begins at 0.05 and ends at 2.5. I want the values in between the min and max to grow by increments of 0.245.

var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];

the final output should be like this:

[0.05, 0.0745, 0.99, 0.1235, 0.148 ... 2.5]
2
  • 2
    I see nothing wrong with your approach so far. Commented Mar 26, 2014 at 9:41
  • How can I create a loop that will produce the final output array? Commented Mar 26, 2014 at 9:42

7 Answers 7

5

using ES6/ES2015 spread operator you can do this way:

let min = 0.05,
    max = 2.5,
    items = 100,
    increments = ((max - min) / items);

let result = [...Array(items + 1)].map((x, y) => min + increments * y);

if you need to round your numbers to x number of digits you can do this way:

let result = [...Array(items + 1)].map((x, y) => +(min + increments * y).toFixed(4));

Here is an example of the code

Sign up to request clarification or add additional context in comments.

Comments

2

do like

var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];


for(var i=min; i<max;i=i+increments) {
    arr.push(i);
}
arr.push(max);

console.log(arr);

Comments

1

Try this:

var min = 0.05;
    var max = 2.5;
    var increments = ((max - min) / 100);
    var arr = [];

    for (var i = min; i < max; i +=increments) {
        arr.push(i);
    }
    arr.push(max);

Comments

1

The basic idea is this:

for (var val=min; val<=max; val+=increments) {
  arr.push(val);
}

Keep in mind that floating point operations often have rounding errors. To fix them, you might want to round the value at each step:

var val = min;
while (val <= max) {
  arr.push(val);

  val += increments;
  val = Math.round(val*1000)/1000; // round with 3 decimals  
}

Comments

1

In some cases you may get wrong results due to rounding errors if you just increment number on each iteration. More correct way is:

var min = 0.05;
var max = 2.5;
var increments = (max - min) / 100;
var arr = [];
for (var i = 0; i <= 100; ++i)
    arr.push(min + increments * i);

Comments

1
function GetArray(minValue, maxValue, step) {
        var resArray = [];
        if (!isNaN(minValue) || !isNaN(maxValue) || !isNaN(step)) {
            for (var i = minValue; i <= maxValue; i=i+step)
            {
                resArray.push(i);
            }
        }
        return resArray;
    }

Comments

0

you can use this function

function test(){
   var min = 0.05;
   var max = 2.5;
    var increments = (max-min)/100;
    var arr = [];
    for(var min=0.05;min<=max;min=min+increments){
            arr.push(min);
    }
   alert(arr);
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.