Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use reduce method in ES6

Shulou Source: shulou.com Published: 2022-06-01 04:58:08 09月27日 Update

This article will explain in detail how to use the reduce method in ES6. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Powerful reduce

The reduce method of an array has a wide range of uses. It is generally used to reduce each item in an array to a single value. But you can do more with it.

1 using reduce to implement map and filter simultaneously

Suppose there is a sequence now, and you want to update each item (the function of map) and filter out a portion (the function of filter). If you use map first and then filter, you need to iterate through the array twice.

In the following code, we double the values in the sequence and pick out the numbers that are greater than 50. Notice how we use reduce very efficiently to accomplish both the map and filter methods?

Const numbers = [10,20,30,40]; const doubledOver50 = numbers.reduce ((finalList, num) = > {num = num * 2; if (num > 50) {finalList.push (num);} return finalList;}, []); doubledOver50; / / [60,80] 2 replace map and filter with reduce

If you read the above code carefully, you should be able to understand that reduce can replace map and filter.

3 use reduce to match parentheses

Another use of reduce is to be able to match parentheses in a given string. For a string with parentheses, we need to know whether the number of parentheses is the same and whether it appears before.

We can easily solve this problem with reduce in the following code. We just need to declare a counter variable with an initial value of 0. When you encounter (counter plus one, encounter), counter minus one. If the number of left and right parentheses matches, the final result is 0.

/ / Returns 0 if balanced.const isParensBalanced = (str) = > {return str.split (''). Reduce ((counter, char) = > {if (counter < 0) {/ / matched ")" before "(" return counter;} else if (char ='(') {return + + counter;} else if (char =') {return-- counter;} else {/ / matched some other char return counter;}, 0); / /

Tags: Array method code facet parenthesis more article statistics number function at the same time character string object sequence number purpose selection good practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft vpn Shulou Tech Info Shulou Information Xiaomi