Table of Contents
es6 reduce() introduction
1、累加和累积乘法
2、获取一个数组的最大值和最小值
3、计算数组中元素出现的频率
4、多个数组的展平
Home Web Front-end Front-end Q&A How to use reduce() in es6

How to use reduce() in es6

Jan 29, 2023 pm 06:35 PM
es6 reduce()

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])
Copy after login

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)
Copy after login

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)
Copy after login

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')
Copy after login

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, '')
Copy after login

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

1、累加和累积乘法

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

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

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

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

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

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

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

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

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

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

一行代码搞定!

How to use reduce() in es6

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

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

很多时候,我们在求和的时候需要加上一个权重,这样更能体现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
Copy after login

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

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

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

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

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

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());
}
Copy after login

注意,我们使用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;                            
}, {})
Copy after login

1How to use reduce() in es6

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

4、多个数组的展平

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is es2015 the same as es6? Is es2015 the same as es6? Oct 25, 2022 pm 06:51 PM

es2015 is es6. The full name of es is "ECMAScript", which is a universal scripting language implemented according to the ECMA-262 standard. The version officially released in June 2015 is officially called ECMAScript2015 (ES2015). Because it is the 6th version of ECMAScript, it can Referred to as es6.

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values ​​support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.

See all articles