title: Map/Reduce on an array of hashes in CouchDB
body: <p>I am looking for a map/reduce function to calculate the status in a Design Document.
  Below you can see an example document from my current database. </p>
  
  <pre><code>{
     "_id": "0238f1414f2f95a47266ca43709a6591",
     "_rev": "22-24a741981b4de71f33cc70c7e5744442",
     "status": "retrieved image urls",
     "term": "Lucas Winter",
     "urls": [
         {
             "status": "retrieved",
              "url": "http://...."
         },
         {
             "status": "retrieved",
              "url": "http://..."
         }
     ],
     "search_depth": 1,
     "possible_labels": {
         "gender": "male"
      },
      "couchrest-type": "SearchTerm"
  }
  </code></pre>
  
  <p>I'd like to get rid of the <code>status</code> key and rather calculate it from the statuses of the urls. 
  My current <code>by_status</code> view looks like the following:</p>
  
  <pre><code>function(doc) {
      if (doc['status']) {
         emit(doc['status'], null);
      }
  }
  </code></pre>
  
  <p>I tried some things but nothing actually works. Right now my <code>Map Function</code> looks like this: </p>
  
  <pre><code>function(doc) {
      if(doc.urls){
          emit(doc._id, doc.urls)
      }
  }
  </code></pre>
  
  <p>And my <code>Reduce Function</code></p>
  
  <pre><code>function(key, value, rereduce){ 
      var reduced_status = "retrieved"
      for(var url in value){
          if(url.status=="new"){
              reduced_status = "new";
          }
      }
      return reduced_status;
  }
  </code></pre>
  
  <p>The result is that I get retrieved everywhere which is definitely not right. </p>
  
  <p>I tried to narrow down the problem and it seems to be that <code>value</code> is no array, when I use the following <code>Reduce Function</code> I get length 1 everywhere, which is impossible because I have 12 documents in my database, each containing between 20 to 200 urls</p>
  
  <pre><code>function(key, value, rereduce){ 
     return value.length;
  }
  </code></pre>
  
  <p><a href="http://img.skitch.com/20100316-qeawxgd5pru8d5i6bprygcsmhf.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20100316-qeawxgd5pru8d5i6bprygcsmhf.jpg</a></p>
  
  <p>What am I doing wrong? (I know I want you to write code for me and I'm feeling guilty, but right now I do the calculation of the statuses in ruby after getting the data from the database. It would be nice to already get the right data from the database)</p>