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

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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
Updated on 19-Apr-2021 11:15:18