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).

Community
  • 1
  • 1
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • 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. – Mitya Jul 13 '12 at 23:03
  • 2
    Notice that JavaScript 1.7 has [Array Comprehension](https://developer.mozilla.org/en/New_in_JavaScript_1.7#Array_comprehensions_%28Merge_into_Array_comprehensions%29), unfortunately are implemented only in Firefox at the moment. I hope we will get soon in other browsers as well (see [harmony](http://wiki.ecmascript.org/doku.php?id=harmony:array_comprehensions) – ZER0 Jul 13 '12 at 23:35

3 Answers3

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];
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Right. Plus I would enclose it in a self-executing function assigned to the variable to protect `nonZero` – elclanrs Jul 13 '12 at 23:14
  • 1
    @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. – Pointy Jul 13 '12 at 23:17
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.

dm03514
  • 54,664
  • 18
  • 108
  • 145
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)];
lucabelluccini
  • 648
  • 6
  • 14