Home>Article>Web Front-end> JavaScript array reduce() method usage example

JavaScript array reduce() method usage example

WBOY
WBOY forward
2022-08-24 09:14:17 1881browse

[Related recommendations:javascript video tutorial,web front-end

Preface

Please let me introduce this method in detail today, I hope it will be helpful to you.

This is the basic usage of reduce:

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)

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.

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.

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

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

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')

This time, we use 's' as param1 when we first call the reducer, and then traverse sequentially starting from the first element array.

So we can rewrite our first code snippet using this syntax.

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

Next, we will enter the actual programming chapter to experience the powerful power of reduce.

1. Accumulation and cumulative multiplication

If we want to get the sum of all elements in the array, what would you do?

Generally speaking, you might write like this:

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

Of course, you may have other ways of writing, but as long as you use a for loop, the code will appear redundant.

Then let’s see what the accumulation function above does:

  • Set the initial sum to zero
  • Take out the first element in the array and find and
  • Cache the result of the previous step in sum
  • Take out other elements in the array in turn and perform the above operations
  • Return the final result

We can see that when we describe the above steps in words, it is obvious that it conforms to the use of reduce. So we can use reduce to rewrite the above code:

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

If you are used to using arrow functions, the above code will look more concise:

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

One line of code!

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

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));

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只能是字符串或符号类型。

这里有两个例子:

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

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

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

4、多个数组的展平

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

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

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

The above is the detailed content of JavaScript array reduce() method usage example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete