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
Determining sum of array as even or odd in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers arr. Our function should return the string 'odd' if the sum of all the elements of the array is odd or 'even' if it's even.
Example
Following is the code ?
const arr = [5, 1, 8, 4, 6, 9];
const assignSum = (arr = []) => {
const sum = arr.reduce((acc, val) => {
return acc + val;
}, 0);
const isSumEven = sum % 2 === 0;
return isSumEven ? 'even' : 'odd';
};
console.log(assignSum(arr));
Output
Following is the console output ?
odd
How It Works
The function uses reduce() to calculate the sum of all array elements, then checks if the sum is even using the modulo operator (%). If sum % 2 === 0, the sum is even; otherwise, it's odd.
Alternative Approach Using for Loop
const checkSumParity = (arr) => {
let sum = 0;
for (let i = 0; i
even
odd
Edge Cases
console.log(assignSum([])); // Empty array
console.log(assignSum([0])); // Single zero
console.log(assignSum([-2, -3])); // Negative numbers
even
even
odd
Conclusion
Both approaches effectively determine if an array's sum is even or odd. The reduce() method provides a more functional programming style, while the for loop offers better readability for beginners.
Advertisements
