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
Adding only odd or even numbers JavaScript
We are required to make a function that given an array of numbers and a string that can take any of the two values "odd" or "even", adds the numbers which match that condition. If no values match the condition, 0 should be returned.
For example:
conditionalSum([1, 2, 3, 4, 5], "even") => 6 conditionalSum([1, 2, 3, 4, 5], "odd") => 9 conditionalSum([13, 88, 12, 44, 99], "even") => 144 conditionalSum([], "odd") => 0
Using Array.reduce() Method
We'll use the Array.prototype.reduce() method to iterate through the array and sum numbers based on the condition:
const conditionalSum = (arr, condition) => {
const add = (num1, num2) => {
if(condition === 'even' && num2 % 2 === 0){
return num1 + num2;
}
if(condition === 'odd' && num2 % 2 === 1){
return num1 + num2;
};
return num1;
}
return arr.reduce((acc, val) => add(acc, val), 0);
}
console.log(conditionalSum([1, 2, 3, 4, 5], "even"));
console.log(conditionalSum([1, 2, 3, 4, 5], "odd"));
console.log(conditionalSum([13, 88, 12, 44, 99], "even"));
console.log(conditionalSum([], "odd"));
6 9 144 0
Alternative Approach Using Filter and Reduce
Here's a cleaner approach that first filters the array based on the condition, then sums the filtered values:
const conditionalSumFiltered = (arr, condition) => {
return arr
.filter(num => condition === 'even' ? num % 2 === 0 : num % 2 === 1)
.reduce((sum, num) => sum + num, 0);
}
console.log(conditionalSumFiltered([1, 2, 3, 4, 5], "even"));
console.log(conditionalSumFiltered([1, 2, 3, 4, 5], "odd"));
console.log(conditionalSumFiltered([13, 88, 12, 44, 99], "even"));
console.log(conditionalSumFiltered([], "odd"));
6 9 144 0
How It Works
Both approaches work by:
- Checking conditions: Using modulo operator (%) to determine if a number is odd (num % 2 === 1) or even (num % 2 === 0)
- Accumulating sum: Adding numbers that match the specified condition
- Handling empty arrays: Returns 0 when no elements match the condition
Conclusion
The filter-reduce approach is more readable and follows functional programming principles. Both methods effectively sum odd or even numbers from an array based on the provided condition.
Advertisements
