Skip to content

Commit 56981a6

Browse files
committed
Merge pull request coffeescript-cookbook#21 from joaomoreno/master
Add "Reducing Arrays" recipe
2 parents 0b0aeab + c2636cc commit 56981a6

File tree

2 files changed

+43
-6
lines changed

2 files changed

+43
-6
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
layout: recipe
3+
title: Reducing Arrays
4+
chapter: Arrays
5+
---
6+
7+
h2. Problem
8+
9+
You have an array of objects and want to reduce them to a value, similar to Ruby's <code>reduce()</code> and <code>reduceRight()</code>.
10+
11+
h2. Solution
12+
13+
You can simply use Array's <code>reduce()</code> and <code>reduceRight()</code> methods along with an anonoymous function, keeping the code clean and readable. The reduction may be something simple such as using the <code>+</code> operator with numbers or strings.
14+
15+
{% highlight coffeescript %}
16+
[1,2,3,4].reduce (x,y) -> x + y
17+
# => 10
18+
{% endhighlight %}
19+
20+
{% highlight coffeescript %}
21+
["words", "of", "bunch", "A"].reduceRight (x, y) -> x + " " + y
22+
# => 'A bunch of words'
23+
{% endhighlight %}
24+
25+
Or it may be something more complex such as aggregating elements from a list into a combined object.
26+
27+
{% highlight coffeescript %}
28+
people =
29+
{ name: '', age: 10 }
30+
{ name: '', age: 16 }
31+
{ name: '', age: 17 }
32+
33+
people.reduce (x, y) ->
34+
x[y.name]= y.age
35+
x
36+
, {}
37+
# => { alec: 10, bert: 16, chad: 17 }
38+
{% endhighlight %}
39+
40+
h2. Discussion
41+
42+
Javascript introduced <code>reduce</code> and <code>reduceRight</code> in version 1.8. Coffeescript provides a natural and simple way to express anonymous functions. Both go together cleanly in the problem of merging a collection's items into a combined result.
43+

wanted-recipes.textile

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,6 @@ h2. Strings
2626

2727
h2. Arrays
2828

29-
* Reducing arrays to values (ruby inject) with reduce # [1..10].reduce (a,b) -> a+b # 55
30-
* Reducing arrays in reverse order # JS reduceRight
31-
{% highlight coffeescript %}
32-
["example", "contrived ", "pretty ", "a ", "is ", "here "].reduceRight (x,y) -> x+y
33-
# => 'here is a pretty contrived example'
34-
{% endhighlight %}
3529
* Testing every element in an array
3630
{% highlight coffeescript %}
3731
evens = (x for x in [0..10] by 2)

0 commit comments

Comments
 (0)