Array.Reduce; The Magical Things You Can Do

Reduce


Reduce is a method that belongs to arrays in Javascript. How the reduce method works is to reduce an array to a single value.

Example 1 – Basic Reduce


Now, you might think that’s useless, but let’s break down the code.

First, you pass a function, which takes an accumulator, the element, and the index. And, you pass a value to be your initial value. Next, for every array element, the initial value is changed by adding to the sum (accumulator). Finally, once all elements are processed, the final value is returned. It’s kind of like a for loop, but you can do much more; you can create modified arrays, implement most array methods, create objects from an array, and more. It’s a very powerful method. Now, let’s demonstrate creating an object.

Example 2 – Object Reduce


Similar to the first example, you change the initial value (the object ‘{}’) by adding a new property, then returning the object. Once all names are processed you have a new object created out of an array. This is extremely powerful, and a lot easier than using a for loop to recreate the object. Not only that, it uses a lot less code!

Once I started using reduce, my code got a lot cleaner; I didn’t have to write long for loops to get the job done.

 

With that in mind, I hope this helps improve your code. Until next time, keep creating!


Sources:

MDN Array Reduce

Fun Fun Function Reduce

Reduce Fiddle

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s