1
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?

2
  • 2
    Just so you're aware: there is no such thing as an associative array in Coffeescript/Javascript. You have an object. Commented Jun 22, 2012 at 2:31
  • 1
    Very thing in javascript is an object. I am using it as an associative array. There are no prototypes and no methods. How would you phrase it? Commented Jun 22, 2012 at 2:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have looked at the example, but did not find one that has the parenthesis like you do. This is just the kind of expression that makes coffeescript brilliant. Thank you.
Sorry, the example link had an error. There are a couple of examples in coffeescript.org of generating arrays with comprehensions, like countdown = (num for num in [10..1]), but i would agree that it's not so obvious that there is a big difference to doing countdown = num for num in [10..1], where countdown will end up being just 1 :P
1

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

2 Comments

I don't think this is right. Try it with chartData = {a: {magnitude: 8}, b: {stuff: 10}, c: {magnitude: 10}}, which I believe is the OP's intent. Yours works with something like chartData = [{magnitude: 8}, {stuff: 10},{magnitude: 10}]
Indeed, I had just assumed chartData was an array instead of an object, given that the index was being ignored. But the OP calls it an 'associative array' which I take to be an object. Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.