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 −

console.log(conditionalSum([1, 2, 3, 4, 5], "even")); => 6
console.log(conditionalSum([1, 2, 3, 4, 5], "odd")); => 9
console.log(conditionalSum([13, 88, 12, 44, 99], "even")); => 144
console.log(conditionalSum([], "odd")); => 0

So, let’s write the code for this function, we will use the Array.prototype.reduce() method here −

Example

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"));

Output

The output in the console will be −

6
9
144
0

Updated on: 21-Aug-2020

713 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements