Scott Whittaker

Frontend Developer

Day job React | side projects Svelte

Sequential array of numbers in JavaScript

One of those quick tests required that I had an array of sequential numbers but I could not be bothered to either type out the array, create a loop to fill it or install a library to handle it for me, for example the _range function from lodash. I just wanted a quick one liner and thought there must be an easier way with es6. It turns out to be nice and easy, see Filling with ascending numbers.

For example…

var iterator = new Array(4).keys();
// Array Iterator {}

[...iterator]; // expand values into array
// [0, 1, 2, 3]

This works because Array.prototype.keys() returns a new Array Iterator object and the spread operator allows an iterable object to be expanded into an array.

As a handy one liner…

var numbers = [...new Array(4).keys()];
// [0, 1, 2, 3]

Note that you can also use Array.from() to achieve the same result as it returns a new array from an iterable object.

var numbers = Array.from(new Array(4).keys());
// [0, 1, 2, 3]

es2015

Just out of interest, the following is the babel generated es2015 code…

'use strict';

function _toConsumableArray(arr) {
    if (Array.isArray(arr)) {
        for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
            arr2[i] = arr[i];
        }
        return arr2;
    } else {
        return Array.from(arr);
    }
}

var numbers = [].concat(_toConsumableArray(new Array(4).keys()));