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 βˆ’

 Live Demo

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
Updated on: 2021-04-17T12:04:02+05:30

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements