Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions chapters/arrays/reducing-arrays.textile
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
layout: recipe
title: Reducing Arrays
chapter: Arrays
---

h2. Problem

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>.

h2. Solution

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.

{% highlight coffeescript %}
[1,2,3,4].reduce (x,y) -> x + y
# => 10
{% endhighlight %}

{% highlight coffeescript %}
["words", "of", "bunch", "A"].reduceRight (x, y) -> x + " " + y
# => 'A bunch of words'
{% endhighlight %}

Or it may be something more complex such as aggregating elements from a list into a combined object.

{% highlight coffeescript %}
people =
{ name: '', age: 10 }
{ name: '', age: 16 }
{ name: '', age: 17 }

people.reduce (x, y) ->
x[y.name]= y.age
x
, {}
# => { alec: 10, bert: 16, chad: 17 }
{% endhighlight %}

h2. Discussion

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.

6 changes: 0 additions & 6 deletions wanted-recipes.textile
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,6 @@ h2. Strings

h2. Arrays

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