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


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

Updated on: 19-Apr-2021

635 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements