skiilaa
skiilaa

Reputation: 1282

How can I add together the values of an array in CoffeeScript?

I have an array of numbers. How can I add them together the easiest way in CoffeeScript?

Upvotes: 2

Views: 407

Answers (3)

John Bolton
John Bolton

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

skiilaa
skiilaa

Reputation: 1282

numbers = [1, 2, 3]
sum = 0
(sum += num for num in numbers) # add each number in array to sum

Upvotes: 2

mu is too short
mu is too short

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

Related Questions