views:

138

answers:

2

Can I order the result of a view by the value, returned by reduced?

{
    "rows": [
        {"key":"bob","value":2},
        {"key":"john","value":3},
        {"key":"zztop","value":1}
     ]
}

I wanna a result like this:

{
    "rows": [
        {"key":"zztop","value":1},
        {"key":"bob","value":2},
        {"key":"john","value":3}

     ]
}
A: 

Don't forget you can store JSON data in the key field. That will help do sorting.

eg.

{
    "rows": [
        {"key":[1, "zztop"],null},
        {"key":[2, "bob"],null},
        {"key":[3, "john"],null}
     ]
}

This CouchDB Wiki page on view collation tells you more about sort ordering.

Here is another page from the CouchDB book on ordering. Best to use floats for your sort value if possible.

andyuk
A: 

you just want to sort the rows array by the value property of each object? you can specify a custom comparison method for the js sort method.

myResult.rows.sort(function (a, b) {
    return parseInt(a.value,10) - parseInt(b.value,10);
});

parameters a and b will each be an entry from the rows array. the method returns an int value of greather than 0, 0, or less than zero. greater than 0 means a should be ordered before b, the opposite for less than 0, and 0 means they are equal.

lincolnk