Home >Web Front-end >JS Tutorial >How to use reduce function in js
The reduce function is used for accumulation operations to obtain a single value: receiving an array, a callback function and an initial value (optional). The callback function handles the accumulator (which stores the accumulated results) and the current element. The initial value is the starting value of the accumulator, which defaults to the first element of the array. Use cases include summing, averaging, concatenating arrays, filtering, and grouping.
Usage of reduce function in JS
The reduce function is a function in JavaScript, used to manipulate an array The elements in are accumulated and finally a single value is obtained. Its usage is as follows:
<code class="javascript">const result = array.reduce(callback, initialValue);</code>
Where:
Callback function
The callback function receives two parameters:
initialValue
initialValue is the initial value of the accumulator. If not specified, the first element of the array will be used as the initial value.
Usage
The reduce function is often used in the following scenarios:
Example
Sum:
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 输出:15</code>
Average:
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const average = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / numbers.length; console.log(average); // 输出:3</code>
Connection array:
<code class="javascript">const names = ['John', 'Mary', 'Bob']; const joinedString = names.reduce((accumulator, currentValue) => accumulator + ', ' + currentValue); console.log(joinedString); // 输出:John, Mary, Bob</code>
Filter array:
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.reduce((accumulator, currentValue) => { if (currentValue % 2 === 0) { accumulator.push(currentValue); } return accumulator; }, []); console.log(evenNumbers); // 输出:[2, 4]</code>
The above is the detailed content of How to use reduce function in js. For more information, please follow other related articles on the PHP Chinese website!