2

Is there an elegant way (without a for loop) to create a sequential array in Javascript which starts from a certain number and has a certain numbers of items. for example:

Start from 2017 and has 4 items will look like:

[2017, 2018, 2019, 2020]

thanks

1 Answer 1

6

You could use Array.from with a callback for the values.

The Array.from() method creates a new Array instance from an array-like or iterable object.

[...]

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

var items = 4,
    start = 2017,
    array = Array.from({ length: items }, (_, i) => start + i);

console.log(array);

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

2 Comments

I just realized, new Array(n).map((x,i)=>i) does not returns values but map of Array.from does. Another WTF in JS
@Rajesh, you get a sparse array with new Array(n). map does not work with missing items.

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.