How to usethe JavaScript reduce method in Javascript

In this approach, we are going to use the inbuilt method of JavaScript that is reduce method which will help to go through one of the input arrays (inputArr1) by calculating the sum of the products by having the multiplication with the elements from both the input arrays at the same index. This will give us the maximum sum of products.

Example: This example shows the use of the above-explained approach.

Javascript




function maxSumProdUsingReduce(inputArr1, inputArr2) {
    if (inputArr1.length !== inputArr2.length) {
        return -1;
    }
  
    inputArr1.sort((a, b) => b - a);
    inputArr2.sort((a, b) => b - a);
  
    let outputSum = inputArr1.reduce(
        (sum, value, index) => {
            return sum + value * inputArr2[index];
        },
        0
    );
  
    return outputSum;
}
  
let array1 = [1, 2, 3];
let array2 = [5, 4, 6];
let result1 = 
    maxSumProdUsingReduce(array1, array2);
console.log(result1);
  
let array3 = [4, 7, 5, 2];
let array4 = [2, 3, 2, 1];
let result2 = 
    maxSumProdUsingReduce(array3, array4);
console.log(result2);


Output

32
41

Time Complexity: O(n log n)

Space Complexity: O(1)



JavaScript Program for Maximum Possible Sum of Products

In this article, we will find and print the maximum possible sum of products in the JavaScript language. We have two arrays, inputArr1, and inputArr2. Both these arrays contain positive numbers and the length of both arrays is similar. We have to write the function where every element in inputArr1 has to be multiplied with exactly one element in the inputArr2 array or vice versa, such that each element from both the arrays should appear exactly once and the sum of their multiplication should be maximum.

Examples:

Input: inputArr1[] = [1, 2, 3], inputArr2[] = [5, 4, 6]
Output: 32
Explanation: The maximum sum of product is obtained by 3*6+2*5+1*4 = 32

Table of Content

  • Using Greedy Algorithm in JavaScript
  • Using Sorting and Multiplying
  • Using JavaScript reduce method

Let’s go through all three approaches with the implementation.

Similar Reads

Approach 1: Using Greedy Algorithm in JavaScript

...

Approach 2: Using Sorting and Multiplying

Here, we are going to use the Greedy Algorithm to find the maximum possible sum of products. We are actually finding the maximum elements from the arrays and then we are multiplying these maximum elements with each other. Using the Infinity we are making sure that each value is used only once....

Approach 3: Using the JavaScript reduce method

...