Home > Web Front-end > JS Tutorial > Learn 5 ways to use the JS reduce() method through examples

Learn 5 ways to use the JS reduce() method through examples

青灯夜游
Release: 2021-01-27 19:16:42
forward
2108 people have browsed it

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 the callback function, and the second is the initial value.

Callback function

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.

  • Accumulator (accumulator) - The return value of the accumulator accumulation callback function.
  • Current Value (current value) - Processes the current element of the array.
  • Current Index (current index) - handles the index of the current element of the array.
  • Source Array (source array)

Current Index and Source Array are optional.

Initial value

If an initial value is specified, the accumulator is set to initialValue 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])
Copy after login

In the code snippet below, the first accumulator (accumulator) is assigned an initial value of 0. currentValue is the element of the numbersArr 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);
Copy after login

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

JavaScript reduce use case

1. Sum all values ​​of the array

In the code below, studentResult The array has 5 numbers. Using the reduce() method, reduce an array to a single value that assigns all values ​​and results of the studentResult array to total.

const studentResult = [67, 90, 100, 37, 60];
 
const total = studentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0);
 
console.log(total); // 354
Copy after login

2. The sum of the values ​​in the object array

Usually, we get the data from the backend as an object array, therefore, the reduce() method helps in management Our front-end logic. In the code below, the studentResult object array has three subjects, here, currentValue.marks takes the score of each subject in the studentResult 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
Copy after login

3. Flatten array

"Flat array" refers to converting a multi-dimensional array into one dimension. In the code below, the twoDArr 2-dimensional array is converted into a oneDArr one-dimensional array. Here, the first [1,2] array is assigned to the accumulator accumulator, and then each remaining element of the twoDArr 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 ]
Copy after login

4. Group objects by attributes

According to the attributes of the object, we can use the reduce() method to divide the object array into several groups. You can clearly understand this concept through the following code snippet. Here, the result object array has five objects, each with subject and marks 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 the push() method adds the current object to pass and fail 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);
Copy after login

Output

{
 pass: [
  { subject: ‘化学’, marks: 59 },
  { subject: ‘应用数学’, marks: 90 },
  { subject: ‘英语’, marks: 64 }
 ],
 fail: [
  { subject: ‘物理’, marks: 41 },
  { subject: ‘高等数学’, marks: 36 }
 ]
}
Copy after login

5. Remove duplicates in array

In the following code snippet, duplicates in plicatedArr are removed . First, an empty array is assigned to the accumulator as the initial value. accumulator.includes() Checks whether each element of the duplicatedArr array is already available in the accumulator. If currentValue is not available in the accumulator, use push() 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 ]
Copy after login

Summary

In this article, we discussed the array reduce() method. The reduce() method is first introduced, and then its behavior is discussed using a simple example. Finally, the five most common use cases of the reduce() 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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template