How can I get a map/reduce result which is sorted within descending order of the “value” value?if also using list function can achieve that?

霸气de小男生 提交于 2019-12-04 06:12:50

问题


I have view map and reduce like this: Map:

   function(doc) {
           if(doc.type){
            var usersLength = doc.users.length;
            for (var i = 0; i < usersLength ; i++) {
                    emit([doc.users[i].userid,doc.Service.ownId], 1);
                }
            }
        }

Reduce:

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

Then invoke the view like this: _design/aaa/_view/getUserId?group=true&group_level=2&startkey=["111111"]&endkey=["111111",{}]

I can get the result set below:

{"rows":[
{"key":["111111",""],"value":7},
{"key":["111111","FFFF26"],"value":1},
{"key":["111111","FFFF44"],"value":7},
{"key":["111111","FFFF34"],"value":2}
]}

However, I want to get the result set above sorted within descending order of the "value" value. if also using list function can achieve that? the following would be expected results:

{"rows":[
{"key":["111111",""],"value":7},
{"key":["111111","FFFF44"],"value":7},
{"key":["111111","FFFF34"],"value":2},
{"key":["111111","FFFF26"],"value":1}
]}

回答1:


If you want to sort the result set you have to one that is sorted by value descending you can sort with a comparator callback:

// ES6 Syntax
let originalResult = {
"rows":[
  {"key":["111111",""],"value":7},
  {"key":["111111","FFFF26"],"value":1},
  {"key":["111111","FFFF44"],"value":7},
  {"key":["111111","FFFF34"],"value":2}
]}

let newResult = {
  rows: originalResult.rows.sort((a, b) => b.value - a.value)
} 


来源:https://stackoverflow.com/questions/38800308/how-can-i-get-a-map-reduce-result-which-is-sorted-within-descending-order-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!