Empower Your Codebase with JavaScript's reduce()

Empower Your Codebase with JavaScript's reduce()

ยท

3 min read

JavaScript's reduce() is one of the most useful built-in higher order functions, along with map and filter, to make developers' life easier but unfortunately not a lot of developers' understand its use-case properly.

In this article, I will walk you through some of the most common use-cases of reduce() with hands-on examples.

With practice you will be able to develop a better mental model to use reduce() efficiently ๐Ÿš€

So what is reduce()

reduce() is a built-in array method in ES6. The function takes the values in an array (from first to the last element) and executes a user-supplied reducer callback function on each element of the array to transform them into a single output.

For example, if we would like to calculate the sum of total numbers in an array we can reduce them as below (most common example ever!):

const numbers = [10, 5, 8, 2, 13, 5];
const total = numbers.reduce((acc, curr) => {
  return acc+curr;
}, 0);
console.log(total); // 43

Let's breakdown the above code:

acc is Accumulator- the first argument in reduce() where acc variable is reassigned to. Accumulator has a default value specified at the end of the function with 0. We are expecting number as an output here so we initialized acc with a number, but it could be an object or an array based on the data structure.

curr is Current Value in numbers array being evaluated by the callback function.

There are two more arguments you can pass:

index - which is basically the Index of the element being currently evaluated.

src is Source Array where we can pass the numbers array itself for executing some custom functionalities inside the callback function.

Where and how to use it

reduce() can be used in any arrays as higher order function. It's very suitable for developers who prefer functional programming over anything. If you use for loops a lot to traverse an array, reduce() could be your ultimate weapon from now on.

Assume, we have an array of patients' record and doctors would like to make a list of patients who are more likely to develop cardiac diseases. Therefore, we must first determine how many of them are smokers and are over 65.

We can simply use filter() to filter patients by age and then map() to return their full names with hospital IDs, right?

But what about using reduce() instead? Think of it! ๐Ÿค”

const patients = [
  {
    firstName: 'John',
    lastName: 'Doe',
    hId: 1234,
    age: 75,
    smoking: true
  },
  {
    firstName: 'Richard',
    lastName: 'Smith',
    hId: 5678,
    age: 70,
    smoking: true
  },
  {
    firstName: 'Jack',
    lastName: 'Ryan',
    hId: 5678,
    age: 55,
    smoking: false
  },
  {
    firstName: 'Carrie',
    lastName: 'Stuart',
    hId: 9011,
    age: 40,
    smoking: false
  }
];

const riskyPatients = patients.reduce((acc, curr) => {
  if (curr.age > 65 && curr.smoking) {
    const patients = `${curr.hId} : ${curr.firstName} ${curr.lastName}`;
    acc.push(patients);
  }
  return acc;
}, []);

console.log(riskyPatients); // [ '1234 : John Doe', '5678 : Richard Smith' ]

So like the above example you can always use reduce() instead of chaining filter() and map() to make your code much cleaner!

Conclusion

I hope now you have some useful knowledge on JavaScript's reduce() and you will use it more in your current or upcoming projects ๐Ÿ˜€.

Keep reducing complex arrays and empower your codebase! ๐Ÿ’ช

Reference

developer.mozilla.org/en-US/docs/Web/JavaSc..

ย