You are viewing the documentation for a prerelease version.

# Re-writing Built-in Reduce Functions

+

Using this model as a template, it is possible to write the full implementation of the built-in functions `_sum` and `_count` when working with the sales data and the standard `map()` function below:

```function(doc, meta)
{
emit(meta.id, null);
}```

The `_count` function returns a count of all the records for a given key. Since argument for the reduce function contains an array of all the values for a given key, the length of the array needs to be returned in the `reduce()` function:

```function(key, values, rereduce) {
if (rereduce) {
var result = 0;
for (var i = 0; i < values.length; i++) {
result += values[i];
}
return result;
} else {
return values.length;
}
}```

To explicitly write the equivalent of the built-in `_sum` reduce function, the sum of supplied array of values needs to be returned:

```function(key, values, rereduce) {
var sum = 0;
for(i=0; i < values.length; i++) {
sum = sum + values[i];
}
return(sum);
}```

In the above function, the array of data values is iterated over and added up, with the final value being returned.
{"ft_lang_label":"__label__en","ft_lang_prob":0.57916486,"math_prob":0.99311304,"size":1060,"snap":"2021-21-2021-25","text_gpt3_token_len":261,"char_repetition_ratio":0.16666667,"word_repetition_ratio":0.010989011,"special_character_ratio":0.26509434,"punctuation_ratio":0.15023474,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.986367,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-05-14T14:26:06Z\",\"WARC-Record-ID\":\"<urn:uuid:afe22d4d-b231-4950-b361-116c04b03d64>\",\"Content-Length\":\"165325\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:3c504c65-bf08-486b-b941-0a37997257f6>\",\"WARC-Concurrent-To\":\"<urn:uuid:52d7c1fe-22a5-4f04-9157-8f6cfacf74bf>\",\"WARC-IP-Address\":\"99.84.189.29\",\"WARC-Target-URI\":\"https://docs.couchbase.com/server/7.0/learn/views/views-writing-rewriting.html\",\"WARC-Payload-Digest\":\"sha1:LL24Z6XHTSHZQUAM5ZC3EOQVC3TGOGZ2\",\"WARC-Block-Digest\":\"sha1:C3GNOYW2YATYEOXW3TXCGVNWJ636ALPD\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-21/CC-MAIN-2021-21_segments_1620243989526.42_warc_CC-MAIN-20210514121902-20210514151902-00238.warc.gz\"}"}