Squared and square rooted sum of numbers of an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function should take each number in the array and square it if it is even, or square root the number if it is odd and then return the sum of all the new numbers rounded to two decimal places.

Example

Following is the code −

 Live Demo

const arr = [45, 2, 13, 5, 14, 1, 20];
const squareAndRootSum = (arr = []) => {
   const res = arr.map(el => {
      if(el % 2 === 0){
         return el * el;
      }else{
         return Math.sqrt(el);
      };
   });
   const sum = res.reduce((acc, val) => acc + val);
   return sum;
};
console.log(squareAndRootSum(arr));

Output

613.5498231854631
raja
Published on 19-Apr-2021 11:12:28
Advertisements