This is the 28th day of my participation in the August Text Challenge.More challenges in August

In real projects, the most common processing is likely to be in computation, loop logic, you can use the array reduce method can also solve a lot of problems, make your code style more elegant!

The reduce of grammar

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

Parameters that

The reducer function needs to receive four parameters, respectively

  • callback

    • Accumulator

      • The return value of the accumulative callback; It is the cumulative value returned when the callback was last called, orinitialValue.
    • Current Value

      • The element in the array being processed.
    • Current Index

      • This is an optional parameter, the index of the current element being processed in the array. If providedinitialValue, the start index is 0; otherwise, the start index is 1.
    • Source Array

      • This is an optional argument to callreduce()An array of
  • initialValue

    • As the first callcallbackThe value of the first argument to the function. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.

The return value

  • The cumulative processing result of the function

Some common Reduce methods

The sum of all the elements in the array
const arr = [1, 2, 3, 4];
const result = arr.reduce((acc, cur) => acc + cur)
​
console.log(result) // 10
Copy the code
Count the number of occurrences of each element in the array
const nums = ['1', '1', '1', '2', '3']; const countednums = nums.reduce((acc, cur) => { if (cur in acc) { acc[cur]++; } else { acc[cur] = 1; } return acc; }, {}); console.log(countednums); {1: 3, 2: 1, 3: 1}Copy the code
Flattening an array
const arr = [['a', 'b'], ['b', 'c'], ['d', 'e']]
const flatten = arr => {
  return arr.reduce((acc, cur) => {
    return acc.concat(cur)
  }, [])
}
​
console.log(flatten(arr)); // ["a", "b", "b", "c", "d", "e"]
Copy the code
Array to heavy
Const arr =,54,4,21,4,4,1,4,4 [22341124]; const result = arr.sort().reduce((acc, cur) => { if(acc.length === 0 || acc[acc.length-1] ! == cur) { acc.push(cur); } return acc; } []); console.log(result); // [1, 124, 21, 22, 341, 4, 54]Copy the code
Find the maximum value in the array
const arr = [1, 2, 3, 5, 1]
let result = arr.reduce((acc, cur) => Math.max(acc, cur))
​
console.log(result)
Copy the code

The last

This article has shared some of the reduce processes that are commonly used in daily development, which you can use directly in your projects or in secondary packaging.

😉 Thanks for reading! Hope to be helpful to your future development! 😉

\