I was wondering what the neatest way would be to convert (from Python) a list comprehension into Javascript. Is there anything which will make this readable and not a mess?
non_zero_in_square = [ grid[row][col]
for row in range(start_row, start_row+3)
for col in range(start_col, start_col+3)
if grid[row][col] is not 0
]
This is quite a good example of a list comprehension, as it has multiple for
s and and an if
.
I should add that the range
bit is covered here (I can't live without range
).
Well it would be somewhat messy to do this with the .map()
method, because the outer calls really need to return arrays. Thus you're probably best with the pedestrian:
var nonZero = [];
for (var row = startRow; row < startRow + 3; ++row)
for (var col = startCol; col < startCol + 3; ++col)
if (grid[row][col] !== 0) nonZero.push(grid[row][col];
Coffee script support list comprehension syntax and is probably the neatest as it follows syntax exactly. Unfortunately it is an intermediary and would be compiled to multi line javascript
http://coffeescript.org/#loops
They show you how it coverts to vanilla javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With