Reputation: 1282
I have an array of numbers. How can I add them together the easiest way in CoffeeScript?
Upvotes: 2
Views: 407
Reputation: 1
Not the fastest implementation, but it is readable:
numbers = [1, 2, 3]
sum = 0
sum += num for num in numbers
Note the similarity to the other answer. This is the correct syntax, and it is identical to:
numbers = [1, 2, 3]
sum = 0
for num in numbers
sum += num
Upvotes: 0
Reputation: 1282
numbers = [1, 2, 3]
sum = 0
(sum += num for num in numbers) # add each number in array to sum
Upvotes: 2
Reputation: 434635
The easiest way is probably to use Array.prototype.reduce
just like you'd do in JavaScript:
numbers = [1..11]
sum = numbers.reduce (m, n) -> m + n
# sum is now 66
Upvotes: 2