Home>Article>Web Front-end> Learn 5 ways to use the JS reduce() method through examples
The reduce() method executes a reducer function (provided by you) on each element in the array, resulting in a single output value.
reduce()
method reduces all elements in an array into a single output value, which can be a number, object, or string.reduce()
The method has two parameters, the first is thecallback function, and the second is theinitial value.
The callback function is executed on each element of the array. The return value of the callback function is the accumulated result and is provided as a parameter for the next call to the callback function. The callback function takes four parameters.
Current Index
andSource Array
are optional.
If an initial value is specified, the accumulator is set toinitialValue
as the initial element. Otherwise, set the accumulator to the first element of the array as the initial element.
arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])
In the code snippet below, the first accumulator (accumulator
) is assigned an initial value of 0.currentValue
is the element of thenumbersArr
array being processed. Here,currentValue
is added to the accumulator and the next time the callback function is called, the return value is provided as a parameter.
const numbersArr = [67, 90, 100, 37, 60]; const total = numbersArr.reduce(function(accumulator, currentValue){ console.log("accumulator is " + accumulator + " current value is " + currentValue); return accumulator + currentValue; }, 0); console.log("total : "+ total);
Output
accumulator is 0 current value is 67 accumulator is 67 current value is 90 accumulator is 157 current value is 100 accumulator is 257 current value is 37 accumulator is 294 current value is 60 total : 354
In the code below,studentResult
The array has 5 numbers. Using thereduce()
method, reduce an array to a single value that assigns all values and results of thestudentResult
array tototal
.
const studentResult = [67, 90, 100, 37, 60]; const total = studentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0); console.log(total); // 354
Usually, we get the data from the backend as an object array, therefore, thereduce()
method helps in management Our front-end logic. In the code below, thestudentResult
object array has three subjects, here,currentValue.marks
takes the score of each subject in thestudentResult
object array.
const studentResult = [ { subject: '数学', marks: 78 }, { subject: '物理', marks: 80 }, { subject: '化学', marks: 93 } ]; const total = studentResult.reduce((accumulator, currentValue) => accumulator + currentValue.marks, 0); console.log(total); // 251
"Flat array" refers to converting a multi-dimensional array into one dimension. In the code below, thetwoDArr
2-dimensional array is converted into aoneDArr
one-dimensional array. Here, the first[1,2]
array is assigned to the accumulatoraccumulator
, and then each remaining element of thetwoDArr
array is connected to the accumulator.
const twoDArr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ]; const oneDArr = twoDArr.reduce((accumulator, currentValue) => accumulator.concat(currentValue)); console.log(oneDArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
According to the attributes of the object, we can use thereduce()
method to divide the object array into several groups. You can clearly understand this concept through the following code snippet. Here, theresult
object array has five objects, each withsubject
andmarks
properties. If the score is greater than or equal to 50, the topic passes, otherwise, the topic fails.
reduce()
Used to group results into passes and failures. First,initialValue
is assigned to the accumulator, then thepush()
method adds the current object topass
andfail
after checking the condition properties as an array of objects.
const result = [ {subject: '物理', marks: 41}, {subject: '化学', marks: 59}, {subject: '高等数学', marks: 36}, {subject: '应用数学', marks: 90}, {subject: '英语', marks: 64}, ]; let initialValue = { pass: [], fail: [] } const groupedResult = result.reduce((accumulator, current) => { (current.marks >= 50) ? accumulator.pass.push(current) : accumulator.fail.push(current); return accumulator; }, initialValue); console.log(groupedResult);
Output
{ pass: [ { subject: ‘化学’, marks: 59 }, { subject: ‘应用数学’, marks: 90 }, { subject: ‘英语’, marks: 64 } ], fail: [ { subject: ‘物理’, marks: 41 }, { subject: ‘高等数学’, marks: 36 } ] }
In the following code snippet, duplicates inplicatedArr
are removed . First, an empty array is assigned to the accumulator as the initial value.accumulator.includes()
Checks whether each element of theduplicatedArr
array is already available in the accumulator. IfcurrentValue
is not available in the accumulator, usepush()
to add it.
const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7]; const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => { if(!accumulator.includes(currentValue)){ accumulator.push(currentValue); } return accumulator; }, []); console.log(removeDuplicatedArr); // [ 1, 5, 6, 7, 8, 9 ]
In this article, we discussed the arrayreduce()
method. Thereduce()
method is first introduced, and then its behavior is discussed using a simple example. Finally, the five most common use cases of thereduce()
method are discussed with examples. If you are a beginner in JavaScript, this article will help you.
English original address: https://medium.com/javascript-in-plain-english/5-use-cases-for-reduce-in-javascript-61ed243b8fef
Author: wathsala danthasinghe
For more programming-related knowledge, please visit:Programming Video! !
The above is the detailed content of Learn 5 ways to use the JS reduce() method through examples. For more information, please follow other related articles on the PHP Chinese website!