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

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

Problem Statement

Given a string of digits, we need to:

  • Separate even and odd digits
  • Calculate the sum of even digits
  • Calculate the sum of odd digits
  • Compare which sum is greater

Example

Let's implement a solution that processes each digit and compares the sums:

const num = '645457345';
const isEvenGreater = (str = '') => {
    let evenSum = 0;
    let oddSum = 0;
    for(let i = 0; i  oddSum;
};
console.log(isEvenGreater(num));
false

How It Works

Let's trace through the example string '645457345':

const num = '645457345';
const analyzeDigits = (str = '') => {
    let evenSum = 0;
    let oddSum = 0;
    let evenDigits = [];
    let oddDigits = [];
    
    for(let i = 0; i  oddSum);
    
    return evenSum > oddSum;
};

analyzeDigits(num);
Even digits: [6, 4, 4]
Even sum: 14
Odd digits: [5, 5, 7, 3, 5]
Odd sum: 25
Is even sum greater? false

Alternative Approach Using Array Methods

We can also solve this using modern JavaScript array methods:

const isEvenGreaterModern = (str = '') => {
    const digits = str.split('').map(Number);
    
    const evenSum = digits
        .filter(digit => digit % 2 === 0)
        .reduce((sum, digit) => sum + digit, 0);
    
    const oddSum = digits
        .filter(digit => digit % 2 !== 0)
        .reduce((sum, digit) => sum + digit, 0);
    
    return evenSum > oddSum;
};

console.log(isEvenGreaterModern('645457345'));
console.log(isEvenGreaterModern('2468'));
console.log(isEvenGreaterModern('13579'));
false
true
false

Comparison

Method Performance Readability Memory Usage
For Loop Faster Good Lower
Array Methods Slower Better Higher

Conclusion

Both approaches effectively solve the problem of comparing even and odd digit sums. The for loop method is more efficient for large strings, while array methods offer better readability and functional programming style.

Updated on: 2026-03-15T23:19:00+05:30

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements