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
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
Advertisements
