Now that you have worked and looked through the posts using higher-order functions like
map()
,filter()
, andreduce()
, you now get to apply them to solve a more complex challenge.Complete the code for the
squareList
function using any combination ofmap()
,filter()
, andreduce()
. 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]
.
const squareList = arr => {
// Only change code below this line
return arr;
// Only change code above this line
};
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
- Hint:
- You will need to filter() the
squareList
for positive integers (decimals are not integers) and you will need tomap()
the values from your filter() function to a variable. - Answer:
const squareList = arr => {
let positiveIntegersSquared = arr.filter(num => {
if (Number.isInteger(num) && num > 0) {
return num;
}
})
.map(num => {
return num * num
});
return positiveIntegersSquared;
};
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
- squareList([-3, 4.8, 5, 3, -3.2]) should return [25, 9].
Top comments (0)