What is the best way to calculate the median of the array?

Should I return an array of data and compute the median in my application or is there a right way to do it in the Couchbase?

1 Answer

« Back to question.

You can make your own functions inside the mapper

  function median(values) { 
     values.sort( function(a,b) {return a - b;} );
     var half = Math.floor(values.length/2);
     if(values.length % 2)
        return values[half];
        return (values[half-1] + values[half]) / 2.0;

The above solution is good if your_array_of_numbers really do not change too much ,
you don't do 10k-1million views calls per second, and if you have hundreds to millions of values in your_array_of_numbers.

Else doing that work will be best / faster in your app layer.

*Note... in the emit() the key is meta.id , so using the GET() from the SDK would also might be better option again.