Categories
Tech News

The ins and outs of JavaScript reducer — a simple, yet powerful array method

JavaScript’s reduce is one of the most useful array methods that should be in a developer’s arsenal. Introduced in ES5, it’s somewhat similar to for…each and map methods that are used with arrays, but improves on their performance and simplicity in specific situations.

The reduce method executes a callback function that we provide on each element stored in an array and outputs the final value the operation generates. It’s a cleaner way of iterating over and processing the data stored in an array.

Currently, it’s supported by all of the major browser versionsand is available in Node.js from version 10.0 upwards.

Today, we are going to explore this reduce method; more specifically, we’ll go through how and when to use it in different scenarios.

Let’s get started then!

Javascript reduce method parameters

The reduce method accepts two arguments: a reducer function for the array that is used as a callback, and an optional initialValue argument. The reducer function takes four arguments: accumulator, currentValue, currentIndex, and array.

An example of Javascript array reduce method in action:

The This reduce method does the same job as the following for…each loop, but with fewer lines of code.

How does the reduce method achieve it using these parameters?

The value returned by the reducer function is assigned to the accumulator variable. In each iteration through the array items, the accumulator’s value is updated to the returned result. At the end of the iteration, the final value of the accumulator is returned as the output of the reduce function.

If an initialValue argument is passed, the first time the reducer function is executed, the accumulator will be equal to initialValue and the currentValue will be equal to the first element stored in the array. If an initialValue is not passed, the accumulator will be equal to the first value of the array and currentValue will be equal to the second.

Let’s see how the values of each of these parameters change every time the callback function is called in the following example. Here, we are not passing an initialValue argument.

The final output of this function is 10.

Next, let’s see how it works when an initialValue is passed.

This function outputs the value 22.

When to use JavaScript’s reducer

The reduce method provides a unique way to iterate through items in an array and process them. So what are the situations in which we can benefit from this uniqueness?

Calculate the sum of values in an array

This is similar to what we did in previous examples. The only difference is we have to pass 0 for the initialValue parameter.

Flatten an array

If we have an array of arrays, we can use the reduce method to flatten it and create a single array without nested arrays.

We pass an empty array as the initial value so the items in the first array are concatenated with it to create a flattened array.

If the first array has more than one level of nested arrays, we can recursively call the reduce function to flatten and then concatenate them with the final array.

If the current value accepted by the callback is an array, as verified using the isArray method, we recursively call the flattenArray function on it. If the current value is not an array, we simply concatenate the value with the final flattened array.

Grouping an array of objects by a property

Assume that we have an array of objects that are basically the names of countries — and we want to group each country in the array according to their continents. We can use the reduce method for this task. Check out the code snippet below:

Inside the callback function, we create a new key for each continent that is not in the groupedCountries map and assign an empty array as its value. Then we push each country object to the array stored by their respective continents.

Using reduce() in place of filter().map()

In JavaScript, we use the filter method to filter items stored in an array using a callback. We use the map method to create a new array using the old array using the logic passed inside a callback. Sometimes we have to use these two methods, one after the other to create a new array with the results we filter using some conditions.

Instead of using two array methods, you can use the JavaScript array reduce method to complete the same task. It will reduce the completion time because now you only iterate through the array only once, not twice.

For example, let’s take the following scenario where we want to create an array of square roots of numbers greater than 30.

The same scenario implemented using reduce looks like this.

Inside the callback, we simply check if the number is greater than 30 and add its square root to the accumulator array. You have to pass an empty array as the initial value to get this result.

Build your own reducer

In this section, we are going to implement the reducer function on our own to see how things work under the hood. This will give you a better idea of when to use the JavaScript reducer for optimal performance in your program.

First, we check if the reduce method was called on a null or undefined object. Then we check if the passed callback is a function.

After the initial type checks, we assign the passed initialValueto the accumulator. Then we loop through the array and call the callback for each item in the array. At the end of execution, we have to return the accumulator value.

We are using this implementation only to help you understand how the reduce method actually works. For example, you can see that it uses a for loop to iterate through the array under the hood.

However, note that you shouldn’t use this implementation in your production code. In fact, prototyping methods to JavaScript standard types is a bad coding practice you should never indulge in.

I hope this knowledge will help you to identify problems that can be resolved with the reducer in the future. Some of these use cases overlap with the forEach , map, and filter array methods. So you should know to pick the situations that can be solved optimally using the reduce method.

This article was originally published on Live Code Stream by Juan Cruz Martinez (twitter: @bajcmartinez), founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things.

Live Code Stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.



Repost: Original Source and Author Link

Categories
Tech News

Samsung outs its new folding Galaxy flip phone in a surprising Oscar ad

Apparently Samsung is as tired of all the leaks as we are. The first Unpacked event of 2020 doesn’t kick off for another day or so, but Samsung has already gone ahead and taken the wraps off its newest phone. In a surprise TV ad rolling moments after Brad Pitt won his first Oscar for Best Supporting Actor, Samsung showed off its latest folding Galaxy phone for the first time.

Update 2/10/20: The post has been updated with a new leak about a supposed Thom Browne edition.

The whimsical 15-second ad was set to French swing song “Comic Strip” by Serge Gainsbourg and features numerous shots of the new phone opening and closing. We didn’t learn much that we didn’t already know, though we did get to see the tint front display in action, so we know for sure you’ll be able to answer or dismiss incoming calls. We also got a clear look at the dual camera, as well as the phone’s purple or black shell.

Samsung’s second folding phone will reportedly be called the Galaxy Z Flip, but it’s unclear whether it’s a follow-up or a companion to the $2,000 Galaxy Fold. With a smaller screen, this phone is rumored to be significantly cheaper.

Hours later, another semi-official ad broke cover, in the form of a partnership with fashion designer Thom Browne. Leaked by Twitter user Walking Cat (@h0x0d), the cryptic ad for Thomas Browne Edition of the Galaxy Z Flip features a male model walking toward a waterfall that parts after he picks up the special-edition Flip, which has the company’s iconic red-white-and-blue stripe down the center of the case. The ad also shows a matching Galaxy Watch and Galaxy Buds, which look to come as a bundle in a special box. 

Just last week, Mototola launched its own foldable flip phone in a revival of the iconic RAZR brand, and based on the images in the ad, the two phones have a very similar look. Motorola’s phone is already off to a bumpy start, however, after it barely lasted 27,000 folds during CNET’s torture test. 

The slogan “Change the shape of the future” appeared just before the end of the ad along with a teaser for Unpacked on February 11. Of note, all of the images shown treated the two screens separately, with the top showing an image and the bottom featuring controls. 

Note: When you purchase something after clicking links in our articles, we may earn a small commission. Read our affiliate link policy for more details.



Repost: Original Source and Author Link