Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehensions nodejs/javascript [duplicate]

Is there anything similar to pythons list comprehension for nodejs/javascript? If there is not then is it possible to make a function that has similar behavior for example

# Example 1

list_one = [[1, 2], [3, 4], [5, 6], [7, 8]]
someOfList = sum(x[1] for x in list_one)
print(someOfList) # prints 20

# Example 2
combined = "".join([str( ( int(x) + int(y) ) % 10) for x, y in zip("9999", "3333")])
print(combined) # prints 2222

Etc? Or would you have to make functions for each comprehension like behavior? I know you can make functions for each of those, but if you use a lot of list comprehensions code can get long

like image 476
user3234209 Avatar asked Jan 27 '14 03:01

user3234209


1 Answers

List comprehensions put into a language's syntax what would normally be done with map and filter.

So given a Python list comprehension, you can also use map and filter:

# Python - preferred way
squares_of_odds = [x * x for x in a if x % 2 == 1]

# Python - alternate way
map(lambda x: x * x, filter(lambda x: x % 2 == 1, a))

although comprehensions are preferred in Python. JavaScript has map and filter so you can use those now.

// JavaScript
a.map(function(x){return x*x}).filter(function(x){return x%2 == 1})

The upcoming version of JavaScript will have array comprehensions in the language:

[ x*x for (x of a) if (x % 2 === 1) ]

To see what is available now in the upcoming version, see this compatibility table. As of this writing, you can see they are available in Firefox.

like image 84
Ray Toal Avatar answered Nov 17 '22 06:11

Ray Toal