Skip to main content

Command Palette

Search for a command to run...

Array.reduce and its Parameters and reduceRight

Published
2 min read
Array.reduce and its Parameters and reduceRight
A

Lately, I've been spending a lot of time learning and implementing micro transitions and animations on web components using state machines to manage component state and have recently had an article featured on Hashnode on XState.

I lead a react learning group, we start at the fundamentals, and work our way up through advanced hooks.

In a previous life, I served as a company founder within the NYC food scene, making me accustomed to fast-paced environments that require sharp attention to detail. I understand the importance of a team and communication within that team.

Array.reduce and its Parameters and reduceRight.

One last useful feature of Array.reduce() are its optional parameters. Let's go through them. There are some occasions when it's useful or necessary to know the index we are on, or you'll need the array itself.

  • A reducer function (required)
  • The Current value (optional). If you don't pass one in, the first value of our array becomes our initial value.
  • The Current index
  • The Array we are iterating over.

Here's another arbitrary example of using the index and array. Imagine you're iterating over a large dataset but you only need to iterate over half of the data. You can do so by using the Array (4th) parameter length method and dividing it by half. When it reaches that index, have it return out of the reducer.

snippet (4).png

There are many uses cases for Array.reduce, the point I'm trying to make is Array.reduce can be pretty useful for some complex logic. In my opinion, make use of built-in methods first, and if you find yourself chaining method after method, consider using a reducer.

Another interesting Array method is Array.reduceRight(). Maybe you're iterating over a new user object and you'd like to see the reduce an array to it's newest users first. We can use Array.reduceRight and it will start at the end of the array, and work it's way in descending order.

I hope these articles have been helpful and stripped away some of the magic of Array.reduce.

Thanks for making it this far.

Ariel

Learning Javascript Reducers the slow way.

Part 5 of 5

Reducers can do a lot more than simply add up numbers in an array. This 5 part series will focus on using reducers to solve some tricky everyday tasks.

Start from the beginning

Understanding Javascript Reducers

What is actually happening when we call Array.reduce()?

More from this blog

Ariel Rodriguez's Dev Blog

12 posts

Lately I've been writing tutorials about web development topic's that interest me, may have stumped me, or something new that I'm just learning.