Home  >  Article  >  Web Front-end  >  How to use reduce() in es6

How to use reduce() in es6

青灯夜游
青灯夜游Original
2023-01-29 18:35:393232browse

In es6, the reduce() function is used to execute a user-provided callback function sequentially from left to right on each element in the array, and summarize its cumulative results into a single return value; syntax " arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])". The reduce() function does not change the original array.

How to use reduce() in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 reduce() introduction

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

First parameter: callback function

Execute each value in the array (if the second parameter initialValue is not provided, (except the first value), containing four parameters:

  • accumulator: The return value of the accumulator accumulation callback; it is the accumulated value returned when the callback was last called, or initialValue (see below).

  • currentValue: The element being processed in the array.

  • currentIndex optional: The index of the current element being processed in the array. If initialValue is provided, the starting index number is 0, otherwise it starts at index 1.

  • array optional: the original array used to call reduce()

Second parameter: initialValue optional

As the value of the first parameter when calling the callback function for the first time. If no initial value is provided, the first element in the array will be used. Note: Calling reduce on an empty array with no initial value will raise an error.

This may seem a bit confusing, but there are actually two situations: one is that the initial value of the second parameter initialValue is given; the other is that no initial value is provided.

var arr = [1, 2, 3];
function reducer(parmar1, parmar2){
}
arr.reduce(reducer)

reduce is a method on the array prototype object that can help us operate the array. It takes another function as its argument, which can be called a reducer.

reducer has two parameters. The first parameter param1 is the result of the last reducer run. If this is the first time the reducer is run, the default value of param1 is the value of the first element of the array.

The reduce method loops through each element in the array, just like in a for loop. And pass the current value in the loop as parameter 2.

After traversing the array, reduce will return the result calculated by the last reducer.

Let’s look at a detailed example.

var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
 return x + y;
}
arr.reduce(add)

How to use reduce() in es6

Next, let’s explore how the above code is executed.

In this code, reducer is add.

First of all, because we are executing add for the first time, the first element 'a' in the array will be used as the first parameter of add, and then the loop will start from the second element 'a' of the array b'start. This time, 'b' is the second argument to add.

How to use reduce() in es6

After the first calculation, we get the result 'ab'. This result will be cached and used as param1 in the next addition calculation. At the same time, the third parameter 'c' in the array will be used as param2 of add.

How to use reduce() in es6

Similarly, reduce will continue to iterate through the elements in the array, running 'abc' and 'd' as arguments to add.

How to use reduce() in es6

Finally, after traversing the last element in the array, return the calculation result.

How to use reduce() in es6

Now we have the result: 'abcde'.

So, we can see that reduce is also a way to traverse an array! It takes the value of each element in the array in turn and executes the reducer function.

But we can see that the above loop does not have that harmonious beauty. Because we take the first element of the array, which is 'a', as the initial param1, and then loop through the second element of the array to get param2.

In fact, we can specify the second parameter in reduce as the initial value of param1 of the reducer function, so that param2 will be obtained in a loop starting from the first element of the array.

The code is as follows:

var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
 return x + y;
}
arr.reduce(add, 's')

How to use reduce() in es6

这一次,我们第一次调用reducer时将's'作为param1,然后从第一个元素开始依次遍历数组。

How to use reduce() in es6

所以我们可以使用这个语法来重写我们的第一个代码片段。

var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
   return x + y;
}
arr.reduce(add, '')

接下来,我们将进入实际编程章节,体验reduce的强大威力。

1、累加和累积乘法

如果我们想得到数组中所有元素的总和,你会怎么做?

一般来说,你可能会这样写:

function accumulation(arr) {
 let sum = 0;
 for (let i = 0; i < arr.length; i++) {
   sum = sum + arr[i];
 }
 return sum;
}

当然,你可能还有其他的写法,但是只要使用for循环,代码就会显得多余。

那我们看看上面的累加函数是做什么的:

  • 将初始总和设置为零
  • 取出数组中的第一个元素并求和
  • 在 sum 中缓存上一步的结果
  • 依次取出数组中的其他元素,进行上述操作
  • 返回最终结果

我们可以看到,当我们用文字描述上述步骤时,很明显它符合reduce的使用。所以我们可以使用reduce来重写上面的代码:

function accumulation(arr) {
 function reducer(x, y) {
   return x + y
 }
 return arr.reduce(reducer, 0);
}

如果你习惯使用箭头函数,上面的代码看起来会更简洁:

function accumulation(arr) {
 return arr.reduce((x, y) => x + y, 0);
}

一行代码搞定!

How to use reduce() in es6

当然,累积乘法和累加是完全一样的:

function multiplication(arr) {
   return arr.reduce((x, y) => x * y, 1);
}

很多时候,我们在求和的时候需要加上一个权重,这样更能体现reduce的优雅。

const scores = [
 { score: 90, subject: "HTML", weight: 0.2 },
 { score: 95, subject: "CSS", weight: 0.3 },
 { score: 85, subject: "JavaScript", weight: 0.5 }
];
const result = scores.reduce((x, y) => x + y.score * y.weight, 0); // 89

2、获取一个数组的最大值和最小值

如果要获取数组的最大值和最小值,可以这样写:

function max(arr){
 let max = arr[0];
 for (let ele of arr) {
   if(ele > max) {
     max = ele;
   }
 }
 return max;
}

这和以前一样,如果我们使用reduce,我们可以在一行代码中完成。

let arr = [3.24, 2.78, 999];
arr.reduce((x, y) => Math.max(x, y));
arr.reduce((x, y) => Math.min(x, y));

How to use reduce() in es6

3、计算数组中元素出现的频率

我们经常需要统计数组中每个元素出现的次数。reduce 方法可以帮助我们实现这一点。

function countFrequency(arr) {
 return arr.reduce(function(result, ele){
   // Judge whether this element has been counted before
   if (result.get(ele) != undefined) {
     /**
       * If this element has been counted before,
       * increase the frequency of its occurrence by 1
       */
     result.set(ele, result.get(ele) + 1)
   } else {
     /**
       * If this element has not been counted before,
       * set the frequency of its occurrence to 1
       */
     result.set(ele, 1);
   }
   return result;
 }, new Map());
}

注意,我们使用map对象而不是对象来存储统计后的频率,因为数组中的元素可能是对象类型,而对象的key只能是字符串或符号类型。

这里有两个例子:

How to use reduce() in es6

1How to use reduce() in es6

同样,如果要统计字符串中每个字符出现的频率,可以先将字符串转换为字符数组,然后按照上面的方法。

let str = &#39;helloworld&#39;;
str.split(&#39;&#39;).reduce((result, currentChar) => {
   result[currentChar] ? result[currentChar] ++ : result[currentChar] = 1;
    return result;                            
}, {})

1How to use reduce() in es6

因为字符类型可以用作对象的键,所以我们这里不使用 Map。

4、多个数组的展平

function Flat(arr = []) {
   return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])
}

1How to use reduce() in es6

通过reduce依次访问数组中的每个元素。如果我们发现元素还是一个数组,就递归调用 flat 方法。

【相关推荐:javascript视频教程web前端

The above is the detailed content of How to use reduce() in es6. 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
Previous article:Is async for es6 or es7?Next article:Is async for es6 or es7?