Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array comprehension in JavaScript? [duplicate]

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

like image 946
Andy Hayden Avatar asked Jul 13 '12 23:07

Andy Hayden


Video Answer


2 Answers

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];
like image 170
Pointy Avatar answered Sep 20 '22 21:09

Pointy


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.

like image 25
dm03514 Avatar answered Sep 17 '22 21:09

dm03514