- 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
Positive integer square array JavaScript
Let’s say, we have an array that contains some numbers, positive, negative, decimals and integers. We have to write a function that takes in an array and returns an array of square of all the positive integers from the original array.
Let’s write the code for this function −
Example
const arr = [1, -4, 6.1, 0.1, 2.6, 5, -2, 1.9, 6, 8.75, -7, 5]; const squareSum = (arr) => { return arr.reduce((acc, val) => { //first condition checks for positivity and second for wholeness of the number if(val > 0 && val % 1 === 0){ acc += val*val; }; return acc; },0); } console.log(squareSum(arr));
Output
The output in the console will be −
87
Advertisements