Home > Net >  How can i add the first index number to n index times in array?
How can i add the first index number to n index times in array?

Time:01-10

I have a variables with the specific values,

    var total = 20;
    var arr = [5];

and i want to divide this variable to get a times of division count,so i added the code to get remainder,

   var inc = Math.ceil(total / arr[0]);

Now If inc value is 4 ,I want to display the variable arr to [5,10,15,20].We have arr[0] is 5 and total is 20, in between two indexes i want to loop.

So, I written a code to get above format,

    for (let i = 1 ; i<=inc - 2; i  ) {
            arr[i] = 5;
            arr[i 1] = total
      }
       console.log(arr) => [ 5, 5, 5, 20 ] I AM GETTING THIS VALUE.

Please help me on these issue.

Thanks in advance

CodePudding user response:

I'd use Array.from with a callback were you do step * counter step to count upwards

var total = 20;
var step  =  5;
var steps = total / step;

const arr = Array.from({ length: steps }, (_, i) => (step * i   step));

console.log(arr);

CodePudding user response:

Your code add 5 multiple times

I changed the for loop :

var total = 20;
var arr = [5];
var inc = Math.ceil(total / arr[0]);

for (let i = 1; i < inc; i  ) {
  arr[i] = arr[i-1]   5;
}
console.log(arr);
  • Related