How to reduce arrays in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to reduce arrays in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: blueviolet;
   }
   button {
      padding: 8px;
   }
</style>
</head>
<body>
<h1>Reduce arrays javascript</h1>
<div><pre class="sample">[1,3,5,6,9,22,15]</pre></div>
<div class="result"></div>
<button class="Btn">Sum</button>
<h3>Click on the above button to sum the elements of the array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 3, 5, 6, 9, 22, 15];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      "Sum = " +
      arr.reduce((sum, prev) => {
         return sum + prev;
      });
   });
</script>
</body>
</html>

Output

On clicking the ‘Sum’ button −

raja
Published on 17-Jul-2020 07:39:37
Advertisements