开发者

Couchdb rereduce understanding and sum

开发者 https://www.devze.com 2023-03-31 18:15 出处:网络
I don\'t know if this is really rereduce but that\'s why I\'m here. I have t开发者_StackOverflow社区his:

I don't know if this is really rereduce but that's why I'm here.

I have t开发者_StackOverflow社区his:

"afrikan" ID: f6733302df85ac109397f4b6030005bf [1, 2]

"afrikan" ID: f6733302df85ac109397f4b6030006d1 [1, 3]

"afrikan" ID: f6733302df85ac109397f4b6030012b6 [2, 4]

"chinese" ID: f6733302df85ac109397f4b6030012eb 1

"chinese" ID: f6733302df85ac109397f4b603001d87 1

I know how to calculate the sum if the value wasn't an array (like in chinese). But I can't manage to sum the values in the array and it results in this: "afrikan" "02,41,31,2"

And one more question: is there a way to sum all the values regardless of keys?

View code:

function(doc) {
  if(doc.food) {
  emit(doc.food, doc.type);
  }
}

Reduce code:

function(keys,values,rereduce) 
{

return sum(values);

}

Thank you a lot :)

UPDATE:

I found an answer for Couchdb.

Here is the code:

function(doc) {
if(doc.food) {
if(doc.type.length>1) {
 doc.type.forEach(function(tag) {
emit(doc.food,tag);
});
}else {
emit(doc.food,doc.type);
}
}
}

Reduce:

function(keys,values) {
return sum(values);
}


The reason you get "02,41,31,2" is because Javascript will convert a number + an array into a string. It is very strange, but true.

> 0 + [2, 4] + [1, 3] + [1, 2]
'02,41,31,2'

> sum([0, [2, 4], [1, 3], [1, 2]]) // Same result
'02,41,31,2'

I think you do not need to worry about rereduce. Just add every value together. If it is an array, add all the values in the array.

function(keys, values, rereduce)
{
  var total = 0;
  var i, j;

  for(i = 0; i < values.length; i++) {
    if(typeof values[i] == "number") {
      total = total + values[i];
    }

    else {
      for(j = 0; j < values[i].length; j++) {
        total = total + values[i][j];
      }
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消