Compute the square of positive integer

Please help me,
How to remove the float number.

function integerSquare(arr){
    var j = [];
    for(var i = 0; i < arr.length; i++){
        if(arr[i] > 0){
            j.push(arr[i] * arr[i]);
        }
    }
    return j;
}
integerSquare([2,-8,2.5,14,-8,1.68,4]);

// [ 4, 6.25, 196, 2.8223999999999996, 16 ]

You are checking for positive numbers but not checking that they are integers

i know but how to check integer

There are ways to do this with array prototype methods: map do replace the existing for loop and filter to handle your problem here, but you are doing it with loops (we could argue about which is better), so I’ll deal with your approach.

On line 4 you have an if statement to decide if to push on the square. You are checking if it is positive. What if you could also check if it was an integer and connect it with an &&?

How do you check if something is an integer?

This is a simple JS test for integer:

let a = 1
let b = 2.3

console.log(a%1===0)
// true

console.log(b%1===0)
// false

Please let us know if you need more help.

3 Likes

thank you so much sir :smile: