A few uses for reduce() in Big Picture JS/TS

A few uses for reduce() in Big Picture JS/TS

Array.prototype.reduce()

The reduce() often causes a common confusion, but it can also make your code much more readable and gives you new space for abstraction.

A simple spell but quite unbreakable , with this we can made a few things and save you a lines of code.

Alt text of image

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value

Reducer on each, you mean forEach? .

At first look the reduce() have behavior as a for loop, but what makes this in something special? , well return a value, extract something from this array without all extra code.

I prefer to use ES6 and Typescript, but if you just look for Javascript, remove the typed properties.

In simple terms .

(cuz talk it's cheap, look at the code)

const numbers = [1, 2, 3, 4];
const simpleSum = (accumulator: number, currentValue: number) => accumulator + currentValue;

console.log(numbers.reduce(simpleSum)); // 10
  • numbers as a simple array of numbers.
  • simpleSum(a, b) is a arrow function that need 2 params:
    • accumulator — the accumulator accumulates all of the callbacks returned values.
    • currentValue — the current value being processed, this mean its the first from position 0 in the array.

The back example made with forEach().

const numbers = [1, 2, 3, 4];
let out = 0; // Yes, need a outside var
numbers.forEach(num => { // Well i not afraid to use arrows func.
      out = num + out; // out += number in short way;
});
console.log(out); // 10

Yeah that doesn't look bad, but you don't use again that extra var out and what happens if you need a sum in other places of your class and what about customization

Of course if you can sum numbers you can be sum strings. This is javascript.

const phrase = ['Hi', 'guys', 'my', 'name', 'is', 'Javier'];

console.log(phrase.reduce((word, w ) => word += ' ' + w));

An easy way for sum its using reduce() .

const customLunch = [
    {
        name: 'Spaghetti with beef',
        price: 20
    },
    {
        name: 'Yogurt and fruits',
        price: 7
    },
    {
        name: 'Protein cereal bar',
        price: 5
    }
];

// a simple sum arrow function
const getTotal = (total: number, itemPrice: number) => total + itemPrice;

// as a good practice use a map() to order by price, this made a new array by the order we define
const prices = customLunch.map(food => food.price);
const totalPrice = prices.reduce(getTotal);

console.log('Total: $'  + totalPrice); // 32

In fact you can set a initial value at the iterate .

This it's really simple, you just need pass a second param with the initial value.

const appleJuicePrice = 4; // We take a juice but not for our lunch
const finalPriceTotal = prices.reduce(getTotal, appleJuicePrice);

console.log('Total: $'  + finalPriceTotal); // 36

And as you can see, the getTotal(a, b) function its reutilized in this other place extending their functionality, where we define the finalPriceTotal with the second param of reduce function to set an initial value.


In other case, an strange case where you need a sum of their properties .

If you want (literally) reduce some lines, using the Object constructor, we can made a lot of things, one of that its get the values of the param (this need be an object).

const basketFruit = {
    apple: { value: 2 },
    orange: { value: 3 },
    pear: { value: 4 },
    watermelon: { value: 1 }
};

const fruits = Object.values(basketFruit); // this made an array
const totalFruits = fruits.reduce((t, { value }) => t + value, 0);

console.log('You have ' + totalFruits + ' fruits');  // 10

In this case, we wrap the current value into {} cuz we have an array of { values } this happen with Object.values().

If you want know more about Object or values


You can reduce any type of data even Dates .

In this example, we have an array of objects that contain a string, from this we made dates and compares them, in this case searching for the most recent date using, of course, the reduce().

const birthsRaw = [
    { birth: '2020/10/31' },
    { birth: '2020/12/25' },
    { birth: '2020/1/2' },
    { birth: '2020/6/4' },
];

// Find the most young using ternary operator
const getYounger = (max: Date, d: Date) => d > max ? d : max; 

const births = birthsRaw.map(a => new Date(a.birth));// We create a new array of Date
const lastBirth = births.reduce(getYounger);

console.dir('Day: ' + lastBirth.toDateString() );  //Day :Fri Dec 25 2020

Summary .

As you can see with these examples, learn how to use the reduction function can be very useful, it will save you a few lines and if you write with good practices you can generalize functions and reuse them.