Higher-Order Functions map, filter, or reduce to Solve a Complex Problem

For this problem, I figured out how to 1) get only positive integers and 2) how to square each item in an array. However, I got stuck on how to get the floats out of the array, so I consulted the Get a Hint section. My solutions for 1) and 2) were very similar to one of the provided solutions and included how to get the floats out of the array.

However, I still don’t understand how this part of the solution works. i % parseInt(i) === 0. What is this part of the solution doing? I read it as "for each item in the array, return the remainder after performing the parseInt method on each item in the array and if the remainder for that operation is 0? I’m getting lost around parseInt. Could someone please translate this into plain English?

Thanks!

const squareList = (arr) => {
  // Only change code below this line
  return arr
          .filter(i => i > 0 && i % parseInt(i) === 0)
          .map(i => Math.pow(i, 2));
  // Only change code above this line
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
  • parseInt(i) converts i to an integer. If i was 3.5, then parseInt(i) would be 3.
  • i % parseInt(i) gets the remainder of i divided by parseInt(i). If i was 3.5 then this would be 0.5.
  • That remainder is then compared to zero, because if i was an integer, then dividing it by parseInt(i) would result in 0.

This is not a particularly efficient (either in terms of code of logic) way to check for an integer. You could, for example, just check if i === parseInt(i). But parseInt() is designed to convert a string to a number, so it actually turns i into a string and then back into a number. You could instead do i === Math.floor(i), for example. You could also use % to find out if it’s an integer by just dividing by 1. ( i % 1 === 0 will be true if i is an integer.)

2 Likes