Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Squared and square rooted sum of numbers of an array in JavaScript
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
Step-by-Step Explanation
Let's break down how this function works:
const arr = [45, 2, 13, 5, 14, 1, 20];
// Step 1: Process each number
// 45 (odd) -> Math.sqrt(45) ? 6.708
// 2 (even) -> 2 * 2 = 4
// 13 (odd) -> Math.sqrt(13) ? 3.606
// 5 (odd) -> Math.sqrt(5) ? 2.236
// 14 (even) -> 14 * 14 = 196
// 1 (odd) -> Math.sqrt(1) = 1
// 20 (even) -> 20 * 20 = 400
const processedArray = arr.map(el => {
return el % 2 === 0 ? el * el : Math.sqrt(el);
});
console.log(processedArray);
[6.708203932499369, 4, 3.605551275463989, 2.23606797749979, 196, 1, 400]
Improved Version with Rounding
The original problem statement mentions rounding to two decimal places. Here's an improved version:
const arr = [45, 2, 13, 5, 14, 1, 20];
const squareAndRootSum = (arr = []) => {
const sum = arr.reduce((acc, el) => {
if(el % 2 === 0){
return acc + (el * el);
} else {
return acc + Math.sqrt(el);
}
}, 0);
return Math.round(sum * 100) / 100; // Round to 2 decimal places
};
console.log(squareAndRootSum(arr));
console.log(`Rounded result: ${squareAndRootSum(arr)}`);
613.55 Rounded result: 613.55
Alternative Using toFixed()
You can also use toFixed() method for consistent decimal formatting:
const squareAndRootSumFixed = (arr = []) => {
const sum = arr.reduce((acc, el) => {
return acc + (el % 2 === 0 ? el * el : Math.sqrt(el));
}, 0);
return parseFloat(sum.toFixed(2));
};
const testArray = [45, 2, 13, 5, 14, 1, 20];
console.log(squareAndRootSumFixed(testArray));
613.55
Conclusion
The function successfully squares even numbers and takes square roots of odd numbers, then sums the results. Remember to round the final sum to two decimal places as specified in the problem requirements.
