Python List Comprehension in Javascript

Getting something similar to Python style list comprehension in Javascript

The javascript spread operator opened my eyes to an easy way to get Python style list comprehension in Javascript.

By creating an array and spreading another array into it while doing some operation on the inner array we effectively have Python style list comprehension.

For example:


    const anArray = [1,2,3];
    console.log([ ...anArray.map(x => x*2)]);

This will print out:

    [ 2, 4, 6 ]

The similar code in Python would be:

     [ n * 2 for n in [1, 2, 3] ]

I actually think that using spread is more readable in some ways. It all makes sense that you can piece together the spread operator with the functional style methods on Arrays to get the same functionality as a list comprehension in Python to me. I like that this "problem" is solved by a combination of basic Javascript functionality instead of creating a new syntax just to add functionality like a list comprehension as well.

Differences with the Python style list comprehension

What I really like about this use of the spread operator in relation to the list comprehension is that you can mix and match the arrays you spread into the new array. With Python I do not believe it is possible to use a single list comprehension to do some ordered concatenation of multiple resulting arrays use a list comprehension.

This is a pretty useful, common operation which makes me appreciate the spread operator.

For example:


    const anArray = [1,2,3];
    const anotherArray = [2,4,6];
    console.log([ ...anArray.map(x => x*2), ...anotherArray.map(x => x/2)]);

This will print out:

    [ 2, 4, 6, 1, 2, 3 ]

The python code for this would require concatenating 2 seperate list comprehensions I believe.

I know you can iterate over multiple lists at the same time in Python but I don't believe you can perform operations on lists and then order the results in any specific manner like the example does above.

Python list comprehension using multiple lists

In Python you can create a list comprehension that results in the combination of every value from the different lists:

    [x + y for x in [1, 3] for y in [2, 4] ]

In Javascript the closest I could get was:

    [1, 3].flatMap(d => [2, 4].map(v => d + v))

Lists or iterables?

Yes, I am saying lists when referring to what the list comprehension is iterating over. Technically, this would be any object which is iterable. An explanation to what makes an object iterable.