DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on • Updated on

Javascript: Reduce

  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);
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
Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

Examples:

1.Flatten array using reduce.

[[1,2],[3,4],[4,5]].reduce((p,n) => p.concat(n));
> [1, 2, 3, 4, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2.Find instances of values in array.

['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}
Enter fullscreen mode Exit fullscreen mode

3.Group objects by property.

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
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

4.Remove duplicate items.

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

> ['a', 'b', 'c']
Enter fullscreen mode Exit fullscreen mode

5.Functional Composition.


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
Enter fullscreen mode Exit fullscreen mode

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

Latest comments (4)

Collapse
 
hitjethva profile image
Hitesh Jethva

Hi,

Can you please give me your email or any contact. I need a parttime writer who can write on JavaScript, React, Vue, Next.js and more.

Collapse
 
hitjethva profile image
Hitesh Jethva

You can contact me on hitjethva@gmail.com

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Cool. My intention is how reduce works.

Collapse
 
azzarox profile image
Azzarox

Is the reduce() function using a recursion behind the scenes ?