List comprehensions in JavaScript

It’s quite well known that list comprehensions exists in many programming languages. This is kind of true for JavaScript, but only with a detour. 

For instance, in Python3 we can do things like,

>>> [i for i in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [i for i in range(10) if i%2 == 0]
[0, 2, 4, 6, 8]

to dynamically create lists. In Haskell we could write,

Prelude> [1..11]
[1,2,3,4,5,6,7,8,9,10,11]
Prelude> [x | x <- [0..10], even x]
[0,2,4,6,8,10]

However, for some reason the from method of Array in JavaScript is not as common. Using from, we can solve similar problems with ease.

> Array.from({length:11}, (_,i) => i + 1);
[1,2,3,4,5,6,7,8,9,10,11]
> const isEven = (x) => x % 2 === 0;
> const identity = (x) => x;
> Array
  .from(
    {length: 10},
    (_, i) => isEven(i) ? i : _
  )
  .filter(identity);
[2,4,6,8]

This means iterating the list twice though, something we might want to avoid if the list is large. Just the same, using from we can simulate more advanced list comprehensions available in other languages.

Leave a Reply