Determining sum of array as even or odd in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 17-Apr-2021 12:03:40
Advertisements