JavaScript Array Reduce

JS
S
JavaScript

The reduce array method iterates through an array and each value of the array will be processed and added (reduced) to an initialValue (accumulator). Accumulator (initial value) can be any of the legacy primitive types and data types: String, Array, Number, Object, Boolean (not sure about Symbol)

1var arr = ['telemetry', 'apm', 'health', 'heartbeat', 'apm'];
2
3// Syntax
4reduce((prev, next) => { return prev + next }, initialValue)
5
6// Basics
7function initialValue():any {
8    return arr.reduce( (prev:any, next:any, index:number) => {
9        console.log('iteration', index);
10        console.warn("prev:",prev);
11        console.warn("next:",next);
12        prev[next] = 1;
13        return prev;
14    },{});
15}
16initialValue(); //array transformed into object with 1 as value for all items
17
18function noInitialValue(){
19    return arr.reduce(function(prev,next){
20        console.log("prev:",prev);
21        console.log("next:",next);
22        return prev + " " +next;
23    });
24}
25noInitialValue(); // long string "apm, telemetry.. "
26
27// UC1 - Count how many times a string is in an array
28function countWords() {
29   return arr.reduce(function(prev, next, index, arrM) {
30      prev[next] = (prev[next]+1) || 1;    // prev = {}, next = arr[0] // prev = {telemetry}, next = arr[1] 
31      return prev;
32   }, {});
33}
34console.log(countWords())

Created on 8/10/2018