Instead of invoking a function on each matching value, I’d like get the array of values ['broccoli', 'spinach'], but I keep getting compiler errors. Could someone explain what I’m misunderstanding?
# Health conscious meal. - This example is from http://coffeescript.org/#loops
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
# Failed Attempt #1 - Unexpected TERMINATOR
arr = for food in foods when food isnt 'chocolate'
# Failed Attempt #2 - Unexpected ')'
arr = (for food in foods when food isnt 'chocolate')
You’re missing the value that the comprehension is supposed to return (which is
eat foodin the original, but you want to returnfoodunmodified). So instead of:You want:
(Though if you’re targeting modern JavaScript implementations, it would probably be more readable just to use something like
foods.filter (food) -> food isnt 'chocolate'.)