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

Top comments (4)

Collapse
 
lukeshiru profile image
Luke Shiru

Just to clarify, you don't need Array.prototype.reduce for all that:

  • Flatten array using reduce: Use Array.prototype.flat instead:
[
    [1, 2],
    [3, 4],
    [4, 5],
].flat(); // [1, 2, 3, 4, 4, 5]
Enter fullscreen mode Exit fullscreen mode
  • Group objects by property: Use Array.prototype.group instead (or a polyfill of it):
[
    { name: "Alex", age: 30 },
    { name: "Max", age: 30 },
    { name: "sony", age: 20 },
    { name: "molly", age: 20 },
].group(({ age }) => age);
Enter fullscreen mode Exit fullscreen mode
  • Remove duplicate items: Use Set instead:
const dedupe = array => [...new Set(array)];

dedupe(["a", "b", "c", "a", "b", "c"]); // ["a", "b", "c"]
Enter fullscreen mode Exit fullscreen mode
  • Functional Composition: Use the pipe operator instead (not implemented yet, but soon ™️):
const times = multiplier => multiplicand => multiplicand * multiplier;
const double = times(2);
const triple = times(3);

const multiply6 = value => double(value) |> triple(%); // Tho tbh here times(6) would be better
Enter fullscreen mode Exit fullscreen mode

The actual real world cases in which Array.prototype.reduce is useful are little. Mainly sums and products, other stuff can be achieved with clearer functions.

Cheers!

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Cool. My intention is how reduce works.

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
 
azzarox profile image
Azzarox

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

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!