'Generate array from 0 to N with custom increment in Javascript
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.
Solution 1:[1]
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);
Solution 2:[2]
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))
Solution 3:[3]
Stumbled upon this, and while looking at the answers I came up with this. This just basically creates an array with incrementing numbers, but could be extended easily.
This reduce function generates desired array by taking the index i of given element and then we combine what we already got in the previous recursive step (the a variable) with the incremental value i.
const arr = new Array(52).fill(0).reduce((a,_,i) => [...a, i],[])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Ph0enixKM |
