Last Updated: November 19, 2020
·
1.822K
· alvarogarcia7

Javascript range / list comprehensions

I was looking how to use a python-equivalent range function. The closest I found is

Array.apply(null, Array(16)).map(
   function (_, i) {
       return i;
    }   
);

//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Source: http://stackoverflow.com/questions/3895478/does-javascript-have-a-range-equivalent

That can also help you create list comprehensions:

Array.apply(null, Array(16)).map(
   function (_, i) {
       var root = i+1;
       var squared = root * root;
       return squared;
    }   
);

//[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]

Related protips:

Flatten a list of lists in one line in Python