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