Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use reduce in JS

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to use reduce in JS. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The reduce method is an iterative method of an array. Unlike map and filter, the reduce method caches a variable. During the iteration, we can manipulate the variable and return it.

This is my explanation in vernacular, but it may not be easy to understand. Let's take a look at the example.

1. Array accumulation

Array accumulation is often encountered in projects, such as calculating the total price of goods, which can be done with one line of code using reduce, and there is no need to define external variables. Reduce is a function with no side effects at all.

/ accumulate [1, 2, 3, 4, 5, 6, 7, 8] .reduce ((a, I) = > a + I); / / output: 36 pluses / accumulate, default an initial value [1, 2, 3, 4, 5, 6, 7, 8] .reduce (a, I) = > a + I, 5); / / output: 41 shock / cumulant [1, 2, 3, 4, 5, 6, 7, 8] .reduce ((a, I) = > a * I) / / output: 403202. Find the maximum value of the array

In each iteration of the array, we use Math.max to get the maximum value and return it, and finally we will get the maximum value of all the items in the array.

[1,2,3,4,5,6,7,8] .reduce (a, I) = > Math.max (a, I))

Of course, if every item in the array is a number, we can use it. The unfold operator fits with Math.max.

Math.max (. [1,2,3,4,5,6,7,8]); 3. Dealing with irregular arrays

The spliced result of each subarray is returned through the combination of map and reduce.

Let data = ["red", "128g", "iPhone"], ["north and south", "two rooms and one hall", "128g", "house house"], ["millet", "white", "smart sports watch", "heart rate, blood pressure and blood oxygen", "caller reminder"], ["official sale", "autumn 2020", "basketball", "sneakers" ["Brand Direct Mail"]] let dataConcat = data.map (item= > item.reduce ((AgraI) = > `$ {a} ${I} `)) / / output result: ["Red 128g iPhone", "128g iPhone", "128g residence with two bedrooms and one living room", "Millet White Smart Sports Watch Heart rate, Blood pressure, Blood oxygen call message reminder", "official Autumn 2020 Basketball shoes Brand Direct Mail"] 4. Delete a data duplicate

Check whether the current iteration item exists, and if not, add it to the array.

Let array = [1,2,3, 'asides,' baked, 'cased, 1,2,3,' asides, 'baked,' c']; array.reduce ((noDupes, curVal) = > {if (noDupes.indexOf (curVal) =-1) {noDupes.push (curVal)} return noDupes}, []) / / output: [1,2,3, 'asides,' baked,'c'] 5. Verify whether the parentheses are legal

This is a very ingenious usage that I have seen on dev.to. If the result equals 0, the number of parentheses is legal.

[. "(()) ())]. Reduce ((a) I) = > I = ='(')? Aqure 1: a status= status 1,0); / / output: 0max / use circular let status=0for (let i of [... "(()) () (() ())]) {if (I = =" (") status= status + 1 else if (I = =") status= status-1 if (status)

< 0) { break; }}6. 按属性分组 按照指定key将数据进行分组,这里我用国家字段分组,在每次迭代过程中检查当前国家是否存在,如果不存在创建一个数组,将数据插入到数组中。并返回数组。 let obj = [ {name: '张三', job: '数据分析师', country: '中国'}, {name: '艾斯', job: '科学家', country: '中国'}, {name: '雷尔', job: '科学家', country: '美国'}, {name: '鲍勃', job: '软件工程师', country: '印度'},]obj.reduce((group, curP) =>

{let newkey = curP ['country'] if (! group [newkey]) {group [newkey] = []} group [newkey] .push (curP) return group}, []) / / output: [China: [{… }, {... }] India: [{... ] United States: [{… }]] 7. Array flattening

The array shown here has only a first-order depth. If the array is multi-level, you can use recursion to process it.

[[3,4,5], [2,5,3], [4,5,6]] .reduce ((singleArr, nextArray) = > singleArr.concat (nextArray), []) / / output: [3,4,5,5,3,4,5,6]

Of course, you can also use ES6's .flat method instead of

[[3,4,5], [2,5,3], [4,5,6] .flat (); 8. Reverse string

This is also a wonderful way to achieve it.

[. "hello world"] .reduce ((ameme v) = > Vajra)

Or

[. "hello world"]. Reverse (). Join (') Thank you for reading! This is the end of the article on "how to use reduce in JS". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report