In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
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); / /
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.