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
How to multiply odd index values JavaScript
We are required to write a function that takes in an array of Number literals as one and the only argument. The numbers that are situated at even index should be returned as it is. But the numbers situated at the odd index should be returned multiplied by their corresponding indices.
For example:
If the input is: [5, 10, 15, 20, 25, 30, 50, 100] Then the function should return: [5, 10, 15, 60, 25, 150, 50, 700]
Understanding the Logic
Let's break down what happens at each index:
- Index 0 (even): 5 remains 5
- Index 1 (odd): 10 × 1 = 10
- Index 2 (even): 15 remains 15
- Index 3 (odd): 20 × 3 = 60
- Index 4 (even): 25 remains 25
- Index 5 (odd): 30 × 5 = 150
- Index 6 (even): 50 remains 50
- Index 7 (odd): 100 × 7 = 700
Using Array.reduce() Method
We will use the Array.prototype.reduce() method to construct the required array:
const arr = [5, 10, 15, 20, 25, 30, 50, 100];
const multiplyOdd = (arr) => {
return arr.reduce((acc, val, ind) => {
if(ind % 2 === 1){
val *= ind;
}
return acc.concat(val);
}, []);
};
console.log(multiplyOdd(arr));
[ 5, 10, 15, 60, 25, 150, 50, 700 ]
Alternative Approach Using Array.map()
A more straightforward approach uses the map() method:
const arr = [5, 10, 15, 20, 25, 30, 50, 100];
const multiplyOddMap = (arr) => {
return arr.map((val, ind) => {
return ind % 2 === 1 ? val * ind : val;
});
};
console.log(multiplyOddMap(arr));
[ 5, 10, 15, 60, 25, 150, 50, 700 ]
Comparison of Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
reduce() |
Complex | Good | When building from scratch |
map() |
Simple | Best | One-to-one transformation |
Conclusion
Both reduce() and map() methods work effectively for multiplying odd index values. The map() method is more readable and better suited for this transformation task.
Advertisements
