Finding the product of array elements with reduce() in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array arr. Our function should find and return the product of all the elements of the array.

Example

Following is the code −

 Live Demo

const arr = [3, 1, 4, 1, 2, -2, -1];
const produceElements = (arr = []) => {
   const res = arr.reduce((acc, val) => {
      acc = acc * val;
      return acc;
   }, 1);
   return res;
};
console.log(produceElements(arr));

Output

Following is the console output −

48
raja
Published on 19-Apr-2021 08:00:47
Advertisements