Array accumulator-reduce, reduceRight

1. Basic grammar

1.reduce

reduce(): Execute a provided reducer function sequentially on each element in the array. Each time the reducer is run, the calculation results of the previous elements are passed in as parameters, and finally the results are summarized into a single return value.

Note : When the callback function is executed for the first time, there is no "last calculation result". If you need the callback function to start executing from the element with array index 0, you need to pass an initial value. Otherwise, the element at array index 0 will be used as the initial value and the iterator will execute starting from the second element (that is, starting at index 1 instead of 0).
reduce(callbackFn, initialValue):
callbackFn:(previousValue, currentValue, currentIndex, array) => value: Function executed for each element in the array. Its return value will be used as the previousValue parameter the next time callbackFn is called. For the last call, the return value will be the return value of reduce(). The following parameters will be passed in when this function is called:

  • previousValue: The result of the last callbackFn call. On the first call, if initialValue is specified, it is the specified value, otherwise it is the value of array[0].
  • currentValue: The value of the current element. On the first call, if initialValue is specified, it is the value of array[0], otherwise it is array[1].
  • currentIndex:The index position of currentValue in the array. On the first call, it is 0 if initialValue is specified, 1 otherwise.
  • array: The array itself on which reduce() was called.

initialValue: (Optional) Initialize the value of previousValue when the callback is called for the first time. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue. If initialValue is not specified, previousValue is initialized to the first value in the array, and callbackFn starts executing with the second value in the array as currentValue. In this case, if the array is empty (no first value to return as previousValue), an error will be thrown.

2.reduceRight

reduceRight(): The basic syntax is similar to reduce(), but accumulation is performed from right to left. On the first call, if initialValue is not set, previousValue is the last value of the array.

2. Specific use

1.reduce

  const arr = [1, 2, 3]
  const sum = arr.reduce((previousValue, currentValue) => {
    
    
    console.log('previousValue:', previousValue);
    console.log('currentValue:', currentValue);
    return previousValue + currentValue
  })
  console.log(sum);

Insert image description here

  const arr = [1, 2, 3]
  const sum = arr.reduce((previousValue, currentValue) => {
    
    
    console.log('previousValue:', previousValue);
    console.log('currentValue:', currentValue);
    return previousValue + currentValue
  }, 0)
  console.log(sum);

Insert image description here

2.reduceRight

  const arr = [1, 2, 3]
  const sum = arr.reduceRight((previousValue, currentValue) => {
    
    
    console.log('previousValue:', previousValue);
    console.log('currentValue:', currentValue);
    return previousValue + currentValue
  }, 0)
  console.log(sum);

Insert image description here

3. Usage scenarios

The main purpose of the reduce design is to implement the summation of numeric arrays in a simple and easy-to-read way. Of course, where reduce can be used, other methods can be used instead. The case here is only used as an introduction.

1. Array summation

  const arr = [1, 2, 3]
  const sum = arr.reduce((previousValue, currentValue) => previousValue + currentValue)
  console.log(sum); // 6

2.Array quadrature

  const arr = [1, 2, 3, 4]
  const product = arr.reduce((previousValue, currentValue) => previousValue * currentValue)
  console.log(product); // 24

Of course, we can also expand our thinking a little and realize some other needs.

3. Count the number of occurrences of each element in the array

  const arr = ['a', 'b', 'c', 'd', 'c', 'b', 'c', 'a']
  const number = arr.reduce((previousValue, currentValue) => {
    
    
    if (previousValue[currentValue]) {
    
    
      previousValue[currentValue] ++
    } else {
    
    
      previousValue[currentValue] = 1
    }
    return previousValue
  }, {
    
    })
  console.log(number);

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43845090/article/details/132336001