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

Hi, I converted the numbers into strings to remove the decimal numbers by creating a regular expression to remove them, but I can’t find a proper regex to do it. Is it a good idea or is it better to change strategy?

Thanks!

const squareList = arr => {
// Modifica il codice solo sotto questa riga
arr = arr.filter(num => num >= 0);
arr = arr.map(num => num.toString());
//Regex to remove decimal numbers
arr = arr.filter(elem => /[]/.test(elem));
return arr;
// Modifica il codice solo sopra questa riga
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0

Challenge: Functional Programming - Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem

Link to the challenge:

There is no such requirement in the challenge:

Complete the code for the squareList function using any combination of map() , filter() , and reduce() . The function should return a new array containing the squares of only the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array of real numbers is [-3, 4.8, 5, 3, -3.2] .

You can look at the tests listed below the challenge. One of them explains what you need to code:

squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]) should return [16, 1764, 36] .

Ok. But how do I remove decimal numbers? My idea is to convert to strings the numbers in order to remove the decimal numbers and after that reconverting to numbers and calculate the squares.

The challenge says:

The function should return a new array containing the squares of only the positive integers (decimal numbers are not integers)

What are postive integers?
12 is a positive integer.
12.55 is not an integer.
-12 is not a positive integer.

Let s take an array for example: [ 12, -12, 12.55, 88 ]. Now, the array with positive integers only would be without the numbers -12 and 12.55: [ 12, 88 ] .

Ok. Right now the code I wrote remove negative numbers (both integers and non-integers) but I still have decimal numbers. For example: [ 12, -12, 12.55, 88 ], passed to the function I wrote gives you back an array like this [12, 12.55, 88], and at this point I don’t now how to remove the non-integers numbers.

Okay, that should not be an issue. Take a look at this and see if it helps: Number.isInteger() - JavaScript | MDN

Now it works. Thanks.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.