Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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
Updated on: 2020-08-21T13:46:49+05:30

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements