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: 21-Aug-2020

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements