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
Selected Reading
Even index sum in JavaScript
We need to write a JavaScript function that calculates the sum of all integers at even indices (0, 2, 4, etc.) in an array, then multiplies this sum by the last element of the array.
Problem Statement
Given an array of integers, find the sum of elements at even indices and multiply by the last element.
Input: [4, 1, 6, 8, 3, 9] Even indices: 0, 2, 4 ? elements: 4, 6, 3 Sum: 4 + 6 + 3 = 13 Last element: 9 Result: 13 × 9 = 117
Solution
const arr = [4, 1, 6, 8, 3, 9];
const evenLast = (arr = []) => {
if (arr.length === 0) {
return 0;
} else {
const evenIndexElements = arr.filter((_, index) => index % 2 === 0);
const sum = evenIndexElements.reduce((a, b) => a + b);
const lastElement = arr[arr.length - 1];
const result = sum * lastElement;
return result;
}
};
console.log(evenLast(arr));
117
Step-by-Step Breakdown
const arr = [4, 1, 6, 8, 3, 9];
// Step 1: Filter elements at even indices
const evenIndexElements = arr.filter((_, index) => index % 2 === 0);
console.log("Even index elements:", evenIndexElements);
// Step 2: Sum the filtered elements
const sum = evenIndexElements.reduce((a, b) => a + b);
console.log("Sum:", sum);
// Step 3: Get last element
const lastElement = arr[arr.length - 1];
console.log("Last element:", lastElement);
// Step 4: Multiply sum by last element
const result = sum * lastElement;
console.log("Final result:", result);
Even index elements: [4, 6, 3] Sum: 13 Last element: 9 Final result: 117
Alternative Approach
We can solve this more efficiently using a single loop:
const evenLastOptimized = (arr = []) => {
if (arr.length === 0) return 0;
let sum = 0;
for (let i = 0; i < arr.length; i += 2) {
sum += arr[i];
}
return sum * arr[arr.length - 1];
};
const arr = [4, 1, 6, 8, 3, 9];
console.log(evenLastOptimized(arr));
117
Edge Cases
// Empty array console.log(evenLast([])); // Single element console.log(evenLast([5])); // Two elements console.log(evenLast([2, 7]));
0 25 14
Conclusion
This solution filters elements at even indices, sums them, and multiplies by the last element. The optimized approach using a single loop is more efficient for large arrays.
Advertisements
