Use Higher-Order Functions map, filter, or reduce

Tell us what’s happening:
Describe your issue in detail here.
Hi,

I used filter and map to solve this question. However, when looking that the solution being provided, I still have a few questions in mind. Please offer some insights!

1. Why is it using two `returns` here?
2. Why cannot use `sqrIntegers.push(num * num)` ?

``````const squareList = arr => {
return arr.reduce((sqrIntegers, num) => {
return Number.isInteger(num) && num > 0
? sqrIntegers.concat(num * num)
: sqrIntegers;
}, []);
};
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36`.

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

Let’s fix the formatting to make this clearer

``````const squareList = arr => {
return arr
.reduce(
(sqrIntegers, num) => {
return Number.isInteger(num) && num > 0 ?
sqrIntegers.concat(num * num) :
sqrIntegers;
},
[]
);
};
``````

The `second return’ is inside of the callback function for the reduce. We can instead write this as

``````const squareList = arr => {
return arr
.reduce(
(sqrIntegers, num) =>
Number.isInteger(num) && num > 0 ?
sqrIntegers.concat(num * num) :
sqrIntegers;,
[]
);
};
``````

Now, the reduce method is making an array, so the return value from the callback must be an array. Push modifies the array, but it does not return the modified array. We could rearrange this again if you want to use push

``````const squareList = arr => {
return arr
.reduce(
(sqrIntegers, num) => {
if (Number.isInteger(num) && num > 0) {
sqrIntegers.push(num * num);
}
return sqrIntegers;
},
[]
);
};
``````

Lots of ways to write equivalent logic so long as you understand how high order methods work and what each built in JS method does. But if any of this isn’t quite clicking, please ask more questions!

1 Like

thanks! got it now :))))

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