开发者

Javascript List reducer for CouchDB

开发者 https://www.devze.com 2023-04-11 02:00 出处:网络
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 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

精彩评论

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