The code is well written, and the Reduce method is indispensable. I use these 10 examples to deepen my learning!

The reduce in the array is like a magic wand. It can do something like black technology. The syntax is as follows:

reduce(callback(accumulator, currentValue[, index, array])[,initialValue])
Copy code

reduce accepts two parameters, callback function and initial value. The initial value is optional. The callback function accepts four parameters: accumulated value, current value, current subscript and current array.

If there is only one parameter of reduce, the accumulated value is the first value in the array at the beginning. If there are two parameters of reduce, the accumulated value is the initial value of the incoming and outgoing initialValue at the beginning. Then, at each iteration, the returned value is used as the accumulator accumulation value of the next iteration.

Most of today's examples may not be ideal solutions to problems. The main purpose is to introduce how to use reduce to solve problems.

Sum multiplication

// Sum
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);
// 30

// There are initialization values
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );
// 35

// If you don't understand the first code, the following code is equivalent to it
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );

// multiplication
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);
Copy code

Finds the maximum value in the array

If you want to use reduce to find the maximum value in the array, you can do this:

[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
Copy code

Above, in each iteration, we return the maximum value between the accumulator and the current item, and finally we get the maximum value of the whole array.

If you really want to find the maximum value in the array, don't have the above one. Use the following one more succinctly:

Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
Copy code

Join nonuniform 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}`))

// result
['The red horse', 
'Plane over the ocean', 
'Chocolate ice cream is awesome', 
'this is a long sentence']
Copy code

Here, we use map to traverse each item in the array. We restore all arrays and restore the array to a string.

Remove duplicates from 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 code

Check whether the current value exists on the accumulator array, if not, return - 1, and then add it.

Of course, you can use Set to quickly delete duplicate values. If you are interested, you can go to Google yourself.

Validation bracket

[..."(())()(()())"].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
 Copy code

This is a cool project, which was brushed in the force buckle 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
}, [])
Copy code

Here, we group the first object array according to the country. In each iteration, we check whether the key exists. If it does not exist, we create an array, then add the current object to the array and return the group array.

You can use it as a function to group 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 code

This is only one layer. If there are multiple layers, it can be solved by recursive functions, but I don't like doing recursive things on JS 😂.

A predetermined method is to use the. flat method, which will do the same thing

[ [3, 4, 5],
  [2, 5, 3],
  [4, 5, 6]
].flat();
Copy code

A positive number that has only a power

[-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 code

Reverse string

const reverseStr = str=>[...str].reduce((a,v)=>v+a)
Copy code

This method applies to 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 code

To illustrate this, let's take an example: (10111) - > 1 + (1 + (1 + (0 + (1 + 0 * 2) * 2) * 2) * 2) * 2.

~After that, I'm the person who wants to go home and set up a stall after retirement. I'll see you next time!

The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Posted on Sun, 21 Nov 2021 15:19:07 -0500 by murali