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