Translated by: Ramgen
Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom. In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.
Reduce in the array is like a magic wand that allows you to do a lot of dark technology-like things. The syntax is as follows:
reduce(callback(accumulator, currentValue[, index, array])[,initialValue])
Copy the code
Reduce takes two arguments, a callback function and an initial value, which is optional. The callback takes four arguments: accumulated value, current value, current subscript, and current array.
If reduce has only one parameter, the accumulated value starts as the first value in the array. If reduce has two parameters, the accumulated value starts as the initialValue of the input and output initialValue. At each iteration, the returned value is then used as an Accumulator value for the next iteration.
Most of these examples today may not be ideal solutions to problems, but the main purpose is to show how to use Reduce to solve problems.
Summation and multiplication
/ / sum [3, 5, 4, 3, 6, 2, 3, 4]. The reduce ((a, I) = > a + I); / / / / a 30 initialization value [3, 5, 4, 3, 6, 2, 3, 4]. The reduce ((a, I) = > a + I, 5); Reduce (function(a, I){return (a + I)}, 0); return (a + I){return (a + I)}, 0); / / multiplication [3, 5, 4, 3, 6, 2, 3, 4]. The reduce ((a, I) = > a * I);Copy the code
Find the maximum value in the 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);
Copy the code
Above, on 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, instead of the one above, use the following one:
Math.max(... [3, 5, 4, 3, 6, 2, 3, 4]);Copy the code
Join heterogeneous arrays
let data = [ ["The","red", "horse"], ["Plane","over","the","ocean"], ["Chocolate","ice","cream","is","awesome"], "This", "is", "a", "long", "sentence"]] let dataConcat = data. The map (item = > item. Reduce ((a, I) = > ` ${a} ${I} `)) / / results [' The red horse', 'Plane over the ocean', 'Chocolate ice cream is awesome', 'this is a long sentence']Copy the code
Here we use a map to iterate over each item in the array, we restore all the arrays, and restore the array to a string.
Removes duplicates from 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 }, [])Copy the code
Checks to see if the current value exists on the accumulator array, returns -1 if not, and then adds it.
Of course, you can use the Set method to quickly delete duplicate values, you can Google yourself.
Verify the brackets
[..."(())()(()())"].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). / / 1Copy the code
This is a cool project, it was previously spawn in force button.
Grouping 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 }, [])Copy the code
Here, we group the first array of objects by country. In each iteration, we check to see if the key exists, and if not, we create an array, then add the current object to that array, and return the array of groups.
You can use it to make a function that groups objects with a specified key.
Flat array
let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce( (singleArr, nextArray) => singleArr.concat(nextArray), []) // Results: [3, 4, 5, 2, 5, 3, 4, 5, 6]Copy the code
This is just one layer, if there are multiple layers, you can use recursive functions to solve it, but I don’t really like doing recursive things on JS 😂.
One preordained method is to use the.flat method, which will do the same thing
[ [3, 4, 5],
[2, 5, 3],
[4, 5, 6]
].flat();
Copy the code
There are only positive powers
[-3, 4, 7, 2, 4].reduce((acc, cur) => { if (cur> 0) { let R = cur**2; acc.push(R); } return acc; } []); // Result [16, 49, 4, 144]Copy the code
Inverted string
const reverseStr = str=>[...str].reduce((a,v)=>v+a)
Copy the code
This method works for any object, not just strings. Call reverseStr(“Hola”) and the output is aloH.
Binary to decimal
Const bin2dec = STR =>[...String(STR)]. Reduce ((acc,cur)=>+cur+acc*2,0) // equivalent to const bin2dec = (STR)=> {return [...String(str)].reduce((acc,cur)=>{ return +cur+acc*2 },0) }Copy the code
To illustrate this point, let’s look at an example: (10111) – > 1 + (1 + (1 + (0 + (1 + 0 * 2 * 2) * 2) * 2) * 2.
~ over, I am brush bowl wisdom, inspirational and so on after retirement, to go home to set the stall, we see next period!
The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.
Original text: dev. The to/ramgendepy /…
communication
Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.
In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.