How to use reduce() function In Javascript

This method uses the reduce() function to accumulate the product of all array elements and then calculates the remainder when divided by a specified number β€˜n’.

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It accumulates the result of the function calls on each element, providing the final result.

Example: This example illustrates finding the remainder of the array multiplication divided by β€˜n’ in JavaScript using the reduce() method.

Javascript




function findRemainder2(arr, n) {
    let product = arr.reduce((acc, val) => {
        acc * val, 1
    });
    return product % n;
}
 
let arr2 = [4, 8, 6, 2];
let n2 = 13;
console.log(findRemainder2(arr2, n2));


Output

NaN

Time Complexity: O(n)

Space Complexity: O(1)

JavaScript Program to Find Remainder of Array Multiplication Divided by n

In JavaScript, the remainder of the array multiplication when divided by the number n can be found by iteration, functional programming or array reduction. , it’s often necessary to calculate the remainder of the product of all elements in an array when divided by a given number β€˜n’. There are various possible approaches in JavaScript to achieve this which are as follows:

Table of Content

  • Using forEach() method
  • Using reduce() function
  • Using functional approach with reduce()
  • Using traditional for loop

Similar Reads

Using forEach() method

This approach iterates through each element of the array using the forEach() method and calculates the remainder of the product of all elements when divided by a given number β€˜n’....

Using reduce() function

...

Using functional approach with reduce()

This method uses the reduce() function to accumulate the product of all array elements and then calculates the remainder when divided by a specified number β€˜n’....

Using traditional for-loop

...