Reverse index value sum of array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Suppose we have an array of numbers like this −

const arr = [3, 6, 7, 3, 1, 4, 4, 3, 6, 7];

This array in the example contains 10 elements, so the index of last element happens to be 9. We are required to write a function that takes in one such array and returns the reverse index multiplied sum of the elements.

Like in this example, it would be something like −

(9*3)+(8*6)+(7*7)+(6*3)+.... until the end of the array.

Therefore, let's write the code for this function −

Example

const arr = [3, 6, 7, 3, 1, 4, 4, 3, 6, 7];
const reverseMultiSum = arr => {
   return arr.reduce((acc, val, ind) => {
      const sum = val * (arr.length - ind - 1);
      return acc + sum;
   }, 0);
};
console.log(reverseMultiSum(arr));

Output

The output in the console will be −

187
raja
Published on 31-Aug-2020 10:10:46
Advertisements