
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding Only Odd or Even Numbers in 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
Advertisements