Finding Sum of Alternate Elements of the Array using JavaScript
Given an array, our task is to find the sum of alternative elements of the array using JavaScript.
Example:
Input: array = { 1, 2, 3, 4, 5, 6, 7, 8}
Output: 16
Explanation:
Sum of alternate elements of array = 1 + 3 + 5 + 7 = 16
Table of Content
Using a for-loop
In this approach, The function sumOAlt initializes a sum variable and iterates through the array, incrementing by 2 to access alternate elements. In each iteration, it adds the current element to the sum. Finally, the function returns the total sum of the alternate elements.
Example: The example below shows how to Find the sum of alternative elements of the array Using a for-loop.
function sumOAlt(arr) {
// Initialize sum
let sum = 0;
// Iterate over array
for (let i = 0; i < arr.length; i += 2) {
// Add to sum
sum += arr[i];
}
return sum;
}
const array1 = [1, 2, 3, 4, 5, 6, 7, 8];
console.log("Sum of alternate elements:",
sumOAlt(array1));
Output
Sum of alternate elements: 16
Time complexity: O(n).
Space complexity: O(1).
Using reduce Method
The function sumOAlt utilizes the reduce() method to iterate through the array. It checks if the current index is even, and then adds the element to the accumulator sum. Finally, it returns the sum of alternate elements in the array using reduce.
Example: The example below shows how to find the sum of alternative elements of the array Using the reduce method.
function sumOAlt(arr) {
// Use the reduce method
return arr.reduce((sum, element, index) => {
if (index % 2 === 0) {
return sum + element;
}
return sum;
}, 0);
}
const array1 = [1, 2, 3, 4, 5, 6, 7, 8];
console.log("Sum of alternate elements:",
sumOAlt(array1));
Output
Sum of alternate elements: 16
Time complexity: O(n)
Space complexity: O(1)
Using Filter and Reduce Methods
In this approach, we first filter out the alternate elements of the array by using the filter method and then calculate their sum using the reduce method. This approach is both concise and efficient, leveraging JavaScript's array methods for a clean solution.
Example:
function sumOfAlternateElements(arr) {
return arr
.filter((_, index) => index % 2 === 0)
.reduce((sum, num) => sum + num, 0);
}
// Examples
const array1 = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(sumOfAlternateElements(array1)); // Output: 16
const array2 = [10, 20, 30, 40, 50];
console.log(sumOfAlternateElements(array2)); // Output: 90
const array3 = [5, 15, 25, 35, 45, 55];
console.log(sumOfAlternateElements(array3)); // Output: 75
Output
16 90 75