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
Write a number array and add only odd numbers?
In JavaScript, you can sum only the odd numbers from an array by using the modulus operator (%) to check if a number is odd, then adding it to a running total.
How It Works
The modulus operator returns the remainder when a number is divided by 2. If the remainder is not equal to 0, the number is odd.
Example: Summing Odd Numbers
<html>
<body>
<script>
var tot = 0;
var a = [1, 45, 78, 9, 78, 40, 67, 76];
for(var i = 0; i < a.length; i++){
if(a[i] % 2 !== 0){
tot += a[i];
}
}
document.write("Sum of odd numbers: " + tot);
</script>
</body>
</html>
Output
Sum of odd numbers: 122
Alternative Method: Using filter() and reduce()
<html>
<body>
<script>
var numbers = [1, 45, 78, 9, 78, 40, 67, 76];
var oddSum = numbers
.filter(num => num % 2 !== 0)
.reduce((sum, num) => sum + num, 0);
document.write("Sum using filter/reduce: " + oddSum);
</script>
</body>
</html>
Output
Sum using filter/reduce: 122
Breakdown of the Logic
In the array [1, 45, 78, 9, 78, 40, 67, 76]:
- Odd numbers: 1, 45, 9, 67
- Even numbers: 78, 78, 40, 76 (skipped)
- Sum: 1 + 45 + 9 + 67 = 122
Conclusion
Use the modulus operator (%) to identify odd numbers in an array. The traditional for loop approach is clear and efficient, while filter() and reduce() provide a more functional programming style.
Advertisements
