Sum of individual even and odd digits in a string number using JavaScript


Problem

We are required to write a JavaScript function that takes in string containing digits and our function should return true if the sum of even digits is greater than that of odd digits, false otherwise.

Example

Following is the code −

 Live Demo

const num = '645457345';
const isEvenGreater = (str = '') => {
   let evenSum = 0;
   let oddSum = 0;
   for(let i = 0; i < str.length; i++){
      const el = +str[i];
      if(el % 2 === 0){
         evenSum += el;
      }else{
         oddSum += el;
      };
   };
   return evenSum > oddSum;
};
console.log(isEvenGreater(num));

Output

false

Updated on: 19-Apr-2021

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements