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
Finding sum of alternative elements of the array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate and return the sum of alternative elements of the array.
For example ?
If the input array is ?
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be ?
1 + 3 + 5 + 7 = 16
Method 1: Using for Loop with Index Check
This approach uses a for loop and checks if the index is even to sum alternative elements:
const arr = [1, 2, 3, 4, 5, 6, 7];
const alternativeSum = (arr = []) => {
let sum = 0;
for(let i = 0; i
16
Method 2: Using for Loop with Step Increment
A more direct approach that increments by 2 to skip alternative elements:
const arr = [1, 2, 3, 4, 5, 6, 7];
const alternativeSum = (arr = []) => {
let sum = 0;
for(let i = 0; i
16
Method 3: Using filter() and reduce()
A functional programming approach using filter and reduce methods:
const arr = [1, 2, 3, 4, 5, 6, 7];
const alternativeSum = (arr = []) => {
return arr
.filter((el, index) => index % 2 === 0)
.reduce((sum, el) => sum + el, 0);
};
console.log(alternativeSum(arr));
16
Testing with Different Arrays
const alternativeSum = (arr = []) => {
let sum = 0;
for(let i = 0; i
40
5
0
18
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| for Loop with Index Check | O(n) | O(1) | Good |
| for Loop with Step Increment | O(n/2) | O(1) | Best |
| filter() and reduce() | O(n) | O(n/2) | Good (Functional) |
Conclusion
The step increment approach (Method 2) is most efficient as it only iterates through alternate elements. Use filter/reduce for functional programming style, though it requires extra memory for the filtered array.
Advertisements
