开发者

Javascript List reducer for CouchDB

The map out puts a key and value, value is a list of two numbers

key1 [1,2]
key1 [4,8]
key2 [1,6]
key2 [2,0]

The reducer i was writ开发者_运维问答ing reduces to

key1 [1+4, 2+8] = key1 [5,10]
key2 [1+2, 6+0] = key2 [3,6]

I wrote this script for reducer

function (key, values) {

    val1 = 0;
    val2 = 0;
  if(values != null)
    for(val in values) {
        val1 += parseInt(val[0]);

        val2 += parseInt(val[1]);
}

return [val1,val2];
}

This does not seem to be working , Am I doing something wrong here ?


Replace val[0] with values[val][0]

or better yet:

function (key, values) {

    var val1 = 0;
    var val2 = 0;
    if(values != null) {
      for(var i = 0; i < values.length; i++) {
        var val = values[i];
        val1 += parseInt(val[0]);

        val2 += parseInt(val[1]);
      }
    }
    return [val1,val2];
}

It's never a good idea to for...in an Array because it has some many other properties.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜