Fresheyeball
Fresheyeball

Reputation: 30015

coffeescript loop through associative array

magnitudeArray = []
for index, dataPoint of chartData
     magnitudeArray.push dataPoint.magnitude if dataPoint.magnitude?

The above code works, but for coffeescript its ugly and un-coffeescripty. First of all, the index var is completely un-used, its just there so I can access the dataPoint var as the result fo the associative array and not the index. Also its three lines! With coffeescript loops arrays are supposed to be writable with one line, off of a loop.

I imagine something like this is possible:

magnitudeArray = for dataPoint of chartData when dataPoint.magnitude?

Do you know of the cleaner coffeescriptier way of doing this?

Upvotes: 1

Views: 953

Answers (2)

nicolaskruchten
nicolaskruchten

Reputation: 27370

You can use 'deconstructing assignment' to compact it down a bit more

magnitudes = (magnitude for i, {magnitude} of chartData when magnitude?)

or even

magnitudes = (m for i, {magnitude: m} of chartData when m?)

Upvotes: 1

epidemian
epidemian

Reputation: 19219

Yes, you should be able to use an array comprehension in this case, though you will need to use a variable for the keys of chartData, which i assume is an object. You can use _ to denote an unused variable (though i don't know if this is common practice in CoffeeScript):

magnitudes = (point.magnitude for _, point of chartData when point.magnitude?)

Example at coffeescript.org.

Upvotes: 1

Related Questions