7

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 fors and and an if.

I should add that the range bit is covered here (I can't live without range).

2
  • 3
    As a JavaScript developer who wouldn't know Python if it came up for a chat at the bus stop, that's some funky ass syntax you Pythonistas have got there. Commented Jul 13, 2012 at 23:03
  • 2
    Notice that JavaScript 1.7 has Array Comprehension, unfortunately are implemented only in Firefox at the moment. I hope we will get soon in other browsers as well (see harmony Commented Jul 13, 2012 at 23:35

3 Answers 3

3

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Right. Plus I would enclose it in a self-executing function assigned to the variable to protect nonZero
@elclanrs yes I agree; this assumes some sort of scope akin to the OP, but if it were some sort of tool then nonZero should be a local variable.
2

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.

Comments

0

Mozilla JS Documentation, ES 1.7 supports them natively.

Example:

var numbers = [1, 2, 3, 4];
var doubled = [i * 2 for (i of numbers)];

1 Comment

You won't find any support today in popular browsers except Firefox: kangax.github.io/compat-table/es6 .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.