![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements