Author: Ramgen
Translator: Front-end Xiaozhi Source: dev
If you have dreams and dry goods, you can search for [Great Relocation to the World] on WeChat and pay attention to this Shuwanzhi who is still washing dishes in the early hours of the morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
The one in the array reduce
is like a magic wand, through which you can do things like black technology. The syntax is as follows:
reduce(callback(accumulator, currentValue[, index, array])[,initialValue])
reduce
Accept two parameters, callback function and initial value, the initial value is optional. The callback function accepts 4 parameters: accumulated value, current value, current subscript, and current array.
If reduce
has only one parameter, then the accumulated value is the first value in the array at the beginning, if reduce
has two parameters, then the accumulated value is in and out at the beginning initialValue
initial value. Then at each iteration, the returned value is used as the accumulator
accumulated value for the next iteration.
Most of these examples today are probably not ideal solutions to the problem, the main purpose is to show how to use reduce
to solve the problem.
Summation and Multiplication
// 求和
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);
// 30
// 有初始化值
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );
// 35
// 如果看不懂第一个的代码,那么下面的代码与它等价
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );
// 乘法
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);
Find the largest value in an array
If you want to use reduce
to find the maximum value in an array, you can do this:
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
Above, in each iteration, we return the maximum value between the accumulator and the current item, and finally we get the maximum value for the entire array.
If you really want to find the maximum value in an array, don't have the above, use the following more concisely:
Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
concatenating uneven arrays
let data = [
["The","red", "horse"],
["Plane","over","the","ocean"],
["Chocolate","ice","cream","is","awesome"],
["this","is","a","long","sentence"]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))
// 结果
['The red horse',
'Plane over the ocean',
'Chocolate ice cream is awesome',
'this is a long sentence']
Here we use map
to iterate over each item in the array, we restore all the arrays, and restore the array to a string.
remove duplicates in an array
let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
return noDupes
}, [])
Check if the current value exists on the accumulator array, return -1
if not, then add it.
Of course, you can use Set
to quickly delete duplicate values. If you are interested, you can go to Google yourself.
verify parentheses
[..."(())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);
// 0
[..."((())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);
// 1
[..."(())()(()()))"].reduce((a,i)=> i==='('?a+1:a-1,0);
// -1
This is a cool project that has been swiped in Likou before.
group by attribute
let obj = [
{name: 'Alice', job: 'Data Analyst', country: 'AU'},
{name: 'Bob', job: 'Pilot', country: 'US'},
{name: 'Lewis', job: 'Pilot', country: 'US'},
{name: 'Karen', job: 'Software Eng', country: 'CA'},
{name: 'Jona', job: 'Painter', country: 'CA'},
{name: 'Jeremy', job: 'Artist', country: 'SP'},
]
let ppl = obj.reduce((group, curP) => {
let newkey = curP['country']
if(!group[newkey]){
group[newkey]=[]
}
group[newkey].push(curP)
return group
}, [])
Here, we group the first array of objects according to country
, in each iteration, we check if the key exists, if not, we create an array, then add the current object to that array , and returns an array of groups.
You can use it to make a function that groups objects by a specified key.
flat array
let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce(
(singleArr, nextArray) => singleArr.concat(nextArray), [])
// 结果:[3, 4, 5, 2, 5, 3, 4, 5, 6]
It's just one layer, if there are multiple layers, it can be solved with recursive functions, but I don't really like doing recursive stuff on JS 😂.
A predetermined method is to use the .flat
method which will do the same
[ [3, 4, 5],
[2, 5, 3],
[4, 5, 6]
].flat();
Only positive numbers with powers
[-3, 4, 7, 2, 4].reduce((acc, cur) => {
if (cur> 0) {
let R = cur**2;
acc.push(R);
}
return acc;
}, []);
// 结果
[16, 49, 4, 144]
reverse the string
const reverseStr = str=>[...str].reduce((a,v)=>v+a)
This method works with any object, not just strings. Call reverseStr("Hola")
, the output result is aloH
.
binary to decimal
const bin2dec = str=>[...String(str)].reduce((acc,cur)=>+cur+acc*2,0)
// 等价于
const bin2dec = (str) => {
return [...String(str)].reduce((acc,cur)=>{
return +cur+acc*2
},0)
}
To illustrate this, let's look at an example: (10111)->1+(1+(1+(0+(1+0*2)*2)*2)*2)*2
.
~End, I am the person who will go home and set up a street stall after I retire. See you in the next issue!
The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool , Fundebug .
Original: https://dev.to/ramgendepy/learn-javascript-reduce-method-with-5-examples-128n
comminicate
If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。