Home > Web Front-end > JS Tutorial > body text

How to use Array.prototype.reduce() method in JavaScript?

PHPz
Release: 2023-09-11 22:53:02
forward
1454 people have browsed it

如何在 JavaScript 中使用 Array.prototype.reduce() 方法?

array.reduce() method is used to reduce the entire array to a single value by performing some tasks on each element. For example, when we want to get the sum of all elements of an array, we need to reduce the entire array to a single value, which is the final sum of all elements of the array.

The array.reduce() method tracks the result value of the previous element. After that, it performs the task on the next element using the resulting value we got from the previous element. The first element of the array takes into account the initial value passed as argument to the result value. In this tutorial, we will learn to use JavaScript’s Array.prototype.reduce() method.

grammar

Users can use the array.reduce() method according to the following syntax.

array.reduce((previousResult, element, index, array) => {
   // perform a task
}, startingValue);
Copy after login

We passed the arrow function as the first parameter value in the above syntax. Arrow functions are used as inline callback functions.

array.reduce(callback, startingValue);
Copy after login

In the above syntax, callback is a callback function.

parameter

  • previousResult - This is the result value we got from performing some operation on the previous array element.

  • element - It is the element at index position in the array.

  • Index - It is the current index of the array element.

  • Array - This is itself an array used in the callback function.

  • startingValue - This is the initial value to initialize the previousResult variable.

  • callback - This is a function that is called for each element in the array.

return value

array.reduce() method returns the final result value after performing certain tasks on all array elements.

Example 1

In the following example, we create an array of numbers and initialize it with some values. After that, we use the array.reduce() method to find the product of all the numbers.

In addition, we also use the inline callback function as the first parameter of the reduce() method. In the callback function, we multiply the value of the previousResult variable element-wise and return it.

<html>
<body>
   <h2>Using the <i>array.reduce()</i> method to find a factorial of a number in JavaScript.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      let factorial = numbers.reduce((previousResult, element) => {
         return previousResult = element * previousResult;
      }, 1)
      output.innerHTML += "The factorial of 10 is " + factorial;
   </script>
</body>
</html>
Copy after login

Example 2

In the following example, we use the array.reduce() method to concatenate all array strings into one string. We use the " " operator to merge the current string element with the previous result into the callback function.

<html>
<body>
   <h2>Using the <i>array.reduce()</i> method to merge all strings of the array in JavaScript.</h2>
   <div id="output"> </div>
   <script>
      let output = document.getElementById('output');  
      let strings = ["Welcome", "To", "the", "TutorialsPoint", "blogs", "!"];
         
      function callback(previousResult, stringElement) {   
         return previousResult + " " + stringElement;  
      }  
      let message = strings.reduce(callback, "");
         
      output.innerHTML += "The Message created from the array of the string values is " + message;
   </script>
</body>
</html>
Copy after login

Example 3

In the example below, we are looking for the sum of element index values. Users can see how we use array indexing in the callback function.

<html>
<body>
   <h2>Using the <i>array.reduce()</i> method.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let numersArray = [20, 30, 40, 50, 60, 70, 80, 90, 100];

      let finalValue = numersArray.reduce((previousResult, element, index, array) => {
         return previousResult + element - index;
      }, 0);
      output.innerHTML += "The resultant value after performing operations on array element is " + finalValue;
   </script>
</body>
</html>
Copy after login

Example 4

In this example, we create an array of objects. Each object of this array contains emp_id, emp_name, and salary. We used the reduce() method to get the total salary of all employees. In the callback function of the reduce() method, we access each object and add the value of its salary attribute to the total variable. Finally, the total salary of all employees is returned.

<html>
<body>
   <h2>Using the <i> array.reduce() </i> method.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let arrayOfObjects = [
         { emp_id: "10", emp_name: "Shubham", salary: 10000 },
         { emp_id: "20", emp_name: "Akshay", salary: 20000 },
         { emp_id: "dfd0", emp_name: "John", salary: 20000 },
         { emp_id: "10", emp_name: "Mukund", salary: 50000 },
         { emp_id: "10", emp_name: "salman", salary: 5000 }
      ]
      let totalSalary = arrayOfObjects.reduce((total, object, index, array) => {
         return total + object.salary;
      }, 0);
      output.innerHTML += "The total salary of all employees is " + totalSalary;
   </script>
</body>
</html>
Copy after login

Users learned to use the Array.prototype.reduce() method to convert an entire array into a single array value. We have seen the use cases of reduce() method through different examples. Additionally, we can use the array.reduce() method to find the minimum and maximum values ​​from an array.

When we call the array.reduce() method with an empty array as a reference, it returns an error.

The above is the detailed content of How to use Array.prototype.reduce() method in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!