Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reverse index value sum of array in JavaScript
Suppose we have an array of numbers like this:
const arr = [3, 6, 7, 3, 1, 4, 4, 3, 6, 7];
This array contains 10 elements, so the index of the last element is 9. We need to write a function that calculates the sum of each element multiplied by its reverse index position.
The reverse index means we multiply each element by (array.length - currentIndex - 1). For our example:
// Element at index 0: 3 * (10-0-1) = 3 * 9 = 27 // Element at index 1: 6 * (10-1-1) = 6 * 8 = 48 // Element at index 2: 7 * (10-2-1) = 7 * 7 = 49 // ... and so on
Using Array.reduce() Method
The most efficient approach uses the reduce() method to iterate through the array and accumulate the sum:
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));
187
Using Traditional For Loop
Here's an alternative approach using a standard for loop:
const arr = [3, 6, 7, 3, 1, 4, 4, 3, 6, 7];
function reverseMultiSumLoop(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i] * (arr.length - i - 1);
}
return total;
}
console.log(reverseMultiSumLoop(arr));
187
Step-by-Step Calculation
Let's break down the calculation for better understanding:
const arr = [3, 6, 7, 3, 1, 4, 4, 3, 6, 7];
function reverseMultiSumDetailed(arr) {
let total = 0;
console.log("Calculations:");
for (let i = 0; i < arr.length; i++) {
const reverseIndex = arr.length - i - 1;
const product = arr[i] * reverseIndex;
total += product;
console.log(`Index ${i}: ${arr[i]} * ${reverseIndex} = ${product}`);
}
console.log(`Total sum: ${total}`);
return total;
}
reverseMultiSumDetailed(arr);
Calculations: Index 0: 3 * 9 = 27 Index 1: 6 * 8 = 48 Index 2: 7 * 7 = 49 Index 3: 3 * 6 = 18 Index 4: 1 * 5 = 5 Index 5: 4 * 4 = 16 Index 6: 4 * 3 = 12 Index 7: 3 * 2 = 6 Index 8: 6 * 1 = 6 Index 9: 7 * 0 = 0 Total sum: 187
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
Array.reduce() |
High | Good | Short |
| For Loop | Medium | Slightly faster | Medium |
Conclusion
The reverse index value sum multiplies each array element by its position from the end. Both reduce() and traditional loops work well, with reduce() being more functional and concise.
