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
JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
For a given list of elements, write a JavaScript program to find the sum of its odd and even indexed elements and then, calculate difference between them.
To solve this problem, we will first separate odd indexed and even indexed elements. After separating them find their sum separately and store it in different variables. Now, we will calculate the difference between these sums to get desired result.
Example Scenario:
Input: list = [11, 21, 31, 41, 51, 61]; Output: difference = 30
Here, odd-indexed items are [21, 41, 61] and their sum is 123. The even-indexed items are [11, 31, 51] and their sum is 93. If you calculate the difference between both sums, you will get 30.
Using for Loop
In this approach, follow the steps mentioned below ?
- Initialize two different variables to store sum of odd-indexed and even-indexed elements.
- Iterate over the given array and check if the current index is odd or even.
- If the index is even then add it to the variable in which you are storing sum of even-indexed elements.
- If the index is odd then add it to the variable in which you are storing sum of odd-indexed elements.
- When the loop gets finished then calculate the difference with the help of Math.abs() method.
Example
The following JavaScript program demonstrates how to find sum of odd and even indexed elements and calculate their difference.
// Function to get the absolute difference
function calculateDifference(arr) {
let oddSum = 0;
let evenSum = 0;
for (let i = 0; i < arr.length; i++) {
if (i % 2 === 0) {
// Even-indexed element
evenSum += arr[i];
} else {
// Odd-indexed element
oddSum += arr[i];
}
}
return Math.abs(oddSum - evenSum);
}
// Creating array to store elements
const array = [11, 21, 31, 41, 51, 61];
// Method call
const absoluteDifference = calculateDifference(array);
console.log('Difference =', absoluteDifference);
// Display the sums for clarity
let oddSum = 0, evenSum = 0;
for (let i = 0; i < array.length; i++) {
if (i % 2 === 0) {
evenSum += array[i];
} else {
oddSum += array[i];
}
}
console.log('Even-indexed sum:', evenSum);
console.log('Odd-indexed sum:', oddSum);
Difference = 30 Even-indexed sum: 93 Odd-indexed sum: 123
The time complexity for the solution is O(n) as n is the length of the input array. The space complexity for the solution is O(1), meaning the code requires a constant amount of additional memory.
Using reduce() Method
The Array.reduce() method in JavaScript takes a reducer function and an optional initial value and returns the result after reducing the specified array. Here, we will pass accumulator which represents previously returned value of the function, current value of the array and current index to the reducer function.
As the reduce() method iterates over the array, it will check the index of each element. If the index is even, it will add the value to the even property of accumulator, otherwise to the odd property. Finally, we will get the absolute difference between the sums of the even-indexed and odd-indexed elements.
Example
In this JavaScript program, we use reduce() method to calculate difference between sums of the even-indexed and odd-indexed elements.
function calculateDifference(arr) {
const sums = arr.reduce((accm, cur_val, index) => {
if (index % 2 === 0) {
accm.evenSum += cur_val;
} else {
accm.oddSum += cur_val;
}
return accm;
}, { oddSum: 0, evenSum: 0 });
return Math.abs(sums.evenSum - sums.oddSum);
}
const array = [74, 23, 61, 34, 62, 60];
const absoluteDifference = calculateDifference(array);
console.log('Array:', array);
console.log('Difference =', absoluteDifference);
// Show breakdown
const breakdown = array.reduce((accm, cur_val, index) => {
if (index % 2 === 0) {
accm.evenSum += cur_val;
} else {
accm.oddSum += cur_val;
}
return accm;
}, { oddSum: 0, evenSum: 0 });
console.log('Even-indexed sum:', breakdown.evenSum);
console.log('Odd-indexed sum:', breakdown.oddSum);
Array: [ 74, 23, 61, 34, 62, 60 ] Difference = 80 Even-indexed sum: 196 Odd-indexed sum: 117
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for Loop | High | Faster | Simple logic, better performance |
| reduce() | Medium | Slightly slower | Functional programming style |
Conclusion
Both approaches effectively calculate the absolute difference between sums of odd and even indexed elements. The for loop method is more straightforward and performs better, while reduce() offers a functional programming approach for those who prefer it.
