Javascript: Reduce
Tags: javascript, beginners, programming, functioa
Published: 2022-09-06 17:43:32

1. Returns single value.
2. Doesn't mutate original array.
3. Doesn't execute the function for empty array elements.
4. Syntax: `array.reduce(function(previousValue, currentValue, currentIndex, arr), initialValue);`

```javascript
const reduceArr = [1,2,3,4];

reduceArr.reduce((total, currentValue) => total+currentValue);
> 10

reduceArr //Doesn't mutate original array
> [1, 2, 3, 4]

reduceArr.reduce((total, currentValue) => total+currentValue, 10); // 10 is Initial value
> 20
```

`previousValue:` value resulting from the previous call to callBackFn. On first call, `initialValue` if specified otherwise `array[0]`.

`currentValue:` value of the current element.On the first call, the value of array[0] if `initialValue` specified otherwise `array[1]`.

`currentIndex:` currentValue index. On first call it is 0 if `initialValue` specified otherwise 1.

```javascript
const array = [10, 20, 30, 40];
function reducer(previousValue, currentValue, index, array) {

const result = previousValue + currentValue;

console.log(`previous: ${previousValue}, current:${currentValue}, index: ${index}, array:  ${array}`);
    return result;
}

array.reduce(reducer);

> previous: 10, current: 20, index: 1, array:  10,20,30,40
> previous: 30, current: 30, index: 2, array:  10,20,30,40
> previous: 60, current: 40, index: 3, array:  10,20,30,40
> 100

```
**Examples:**

1.Flatten array using reduce.
```javascript
[[1,2],[3,4],[4,5]].reduce((p,n) => p.concat(n));
> [1, 2, 3, 4, 4, 5]
```

2.Find instances of values in array.
```javascript
['first', 'second', 'third', 'first', 'fourth', 'second'].reduce((list, name) => {
    if(name in list) {
        list[name]++;
    } else {
        list[name] = 1;
    }
        return list;
    }, {});
> {first: 2, second: 2, third: 1, fourth: 1}
```

3.Group objects by property.
```javascript
const obj = [
    {name: 'Alex',age: 30},
    {name: 'Max', age: 30},
    {name: 'sony', age: 20},
    {name: 'molly', age: 20}
    ];

function groupByProperty(array, prop) {
    return array.reduce((list, current) => {
    let key = current[prop];
        if(!list[key]) {
            list[key] = [];
            }
        list[key].push(current);
        return list;
    }, {})};

groupByProperty(obj, 'age');

> {
    "20": [
        {
            "name": "sony",
            "age": 20
        },
        {
            "name": "molly",
            "age": 20
        }
    ],
    "30": [
        {
            "name": "Alex",
            "age": 30
        },
        {
            "name": "Max",
            "age": 30
        }
    ]
}
```

4.Remove duplicate items.
```javascript
['a', 'b', 'c', 'a', 'b','c'].reduce((previous, current) => {
    if(previous.indexOf(current) === -1) {
        previous.push(current);
    }
    return previous;
}, []);

> ['a', 'b', 'c']
```

5.Functional Composition.
```javascript

const double = x => x+x;
const triple = x => 3 * x;

const pipe = (...functions) => input => functions.reduce((acc, fn, index) => {
console.log(`iteration: ${index}, accValue: ${acc}`);
    return fn(acc)},input);

const multiply6 = pipe(double, triple);

multiply6(6);

> iteration: 0, accValue: 6
> iteration: 1, accValue: 12
> 36
```

You can follow me here: https://twitter.com/urstrulyvishwak