Home  >  Article  >  Web Front-end  >  How to use reduce method in javascript

How to use reduce method in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-10 13:47:532861browse

In JavaScript, reduce is a merge method, and the syntax format is "array.reduce(function(previous value, current value, index, array object){}, initial value)". The reduce method receives a function as an accumulator, and each value in the array is reduced to a single value.

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Different from the iteration methods in the previous two articles (implementation of map(), implementation of filter()), reduce() is a merging method.

reduce receives two parameters:

The first parameter is the function called on each item

This function receives 4 parameters:

  • Previous value prev

  • Current value cur

  • The index index of the item

  • Array object array

The second optional parameter is used as the basis for merging The initial value

reduce method returns a final value.

Code representation:

arr.reduce(function(prev, cur, index, arr){}, initialValue)

Merge

Different from the previous iteration, the merge does not execute the target function for each item, but can be summarized into the following two steps:

  • Continuously "take out" the first two items of the array, execute the target function on them, and calculate the return value

  • Put the above return value "Fill back" the head of the array as a new array[0]

  • Continue to execute this process in a loop until each item in the array has been accessed once

  • Return the final result

Example

Merge execution of array [1, 2, 3] (prev, cur) => prev cur, process As shown in the picture:

[1, 2, 3] // 取出 1 + 2 ,填回 3
[3, 3] // 取出 3 + 3 ,填回 6
[6] // 最终结果为 6

So we get 6.

Implementation

First version

According to this idea, the first version of the code is as follows

// 第一版
Array.prototype.fakeReduce = function fakeReduce(fn, base) {
  // let arr = base ? this.unshift(base) : this;// 首进,返回新数组的长度,影响原数组 故不能这么写
  let initialArr = this;
  let arr = initialArr.concat(); //得到副本

  if (base) arr.unshift(base); // 当存在归并基础值的参数时,将其从数组首部推入
  let index;

  while (arr.length > 2) {
    index = initialArr.length - arr.length + 1;
    let newValue = fn.call(null, arr[0], arr[1], index, initialArr);
    arr.splice(0, 2); // 删除前两项,影响原数组
    arr.unshift(newValue);// 把 fn(arr[0],arr[1]) 的结果从数组首部推入
  }
  index += 1;
  let result = fn.call(null, arr[0], arr[1], index, initialArr);
  return result;
};

Note:

Queue method unshift()

You can add any item from the head of the array. The return value is the length of the new array, which affects the original array.

splice() method, Gao Chengsan praised it as the most Powerful array method

Delete any number of items

Specify 2 parameters: (Delete starting position, number of deleted items)

Insert any number of items

Specify 3 parameters: (starting position, 0, item to be inserted)

The second parameter 0 is the number to be deleted

Replacement, that is, deletion Insert any number of items while inserting any number of items

Specify 3 parameters: (starting position, number to be deleted, any number of items to be inserted)

Return value Always an array containing the items removed from the original array. If no items are deleted, an empty array is returned, affecting the original array

Improved version

As can be seen from the above summary, the splice() method can completely replace the unshift() method.

Also, there are some duplicate codes in the first version, which can also be improved.

Get the second version of the code

// 第二版
Array.prototype.fakeReduce = function fakeReduce(fn, base) {

  let initialArr = this;
  let arr = initialArr.concat();

  if (base) arr.unshift(base);
  let index, newValue;

  while (arr.length > 1) {
    index = initialArr.length - arr.length + 1;
    newValue = fn.call(null, arr[0], arr[1], index, initialArr);

    arr.splice(0, 2, newValue); // 直接用 splice 实现替换
  }

  return newValue;
};

Detection:

let arr = [1, 2, 3, 4, 5];
let sum = arr.fakeReduce((prev, cur, index, arr) => {
  console.log(prev, cur, index, arr);
  return prev * cur;
}, 100);

console.log(sum);

Output:

100 1 0 [ 1, 2, 3, 4, 5 ]
 100 2 1 [ 1, 2, 3, 4, 5 ]
 200 3 2 [ 1, 2, 3, 4, 5 ]
 600 4 3 [ 1, 2, 3, 4, 5 ]
 2400 5 4 [ 1, 2, 3, 4, 5 ]
 12000

Finally add type detection, etc.

// 第三版
Array.prototype.fakeReduce = function fakeReduce(fn, base) {
  if (typeof fn !== "function") {
    throw new TypeError("arguments[0] is not a function");
  }
  let initialArr = this;
  let arr = initialArr.concat();

  if (base) arr.unshift(base);
  let index, newValue;

  while (arr.length > 1) {
    index = initialArr.length - arr.length + 1;
    newValue = fn.call(null, arr[0], arr[1], index, initialArr);

    arr.splice(0, 2, newValue); // 直接用 splice 实现替换
  }

  return newValue;
};

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to use reduce method in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn