Home > Back-end >  Generate array from 0 to N with custom increment in Javascript
Generate array from 0 to N with custom increment in Javascript

Time:09-28

Problem Description

I am trying to generate an array using keys() and .map() methods, given a preexisting array with length = arrLength, such that only items at a position that are multiples of step are generated. Here is an example,

const arrLength = 20;
const step = 5;

const newArr = [...Array(arrLength).keys() ].map((i) => i   step);

console.log(newArr) ;
// expected: 0,5,10,15,20
// recieved : 5,6,7,...,24

I am particlarly confused as to how to increment the left hand side variable i in map((i) => ... ).

Restrictions

I want to implement this in one line using the keys method and Array and possibly map, so no for loop.

Things I have tried

I tried the following signatures instead

    Array(arrLength).fill().map((_, i) => i step) ,
    Array.from(Array(arrLength), (_, i) => i step),
    Array.from({ length: arrLength }, (_, i) => i step)

but with no success. I have further tried to find a way to increment the i variable using functional syntax but with no success as wel.

CodePudding user response:

const arrLength = 20;
const step = 5;
const arr = [];
for (let i = 0; i<= arrLength; i =step){
  arr.push(i);
}
console.log(arr);

Or

const arrLength = 20;
const step = 5;

const newArr = [...Array(Math.floor(arrLength/step)   1).keys() ].map((i) => i * step);
console.log(newArr);

CodePudding user response:

range function work with ES4 Using Array.from can pass an object has property length in it

const range = (start, stop, step) => Array.from({ length: (stop - start) / step   1}, (_, i) => start   (i * step));
console.log(range(0, 20, 5))

  • Related