Tell us what’s happening:
Hi guys. So I already solved the challenge by having a look at the hints and figuring out I was only off by a bit. Thing is this: the code below solves all problems except for this:
squaredIntegers = squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])
// [9, 100, 49] expected output
instead it returns [9,100,49,0.09]
My question is: why? I get that having two filter methods is stupid and I changed it after having a look at the solution. But I do not understand why n%parseInt(n) works for every case except this.
Okay nevermind, while writing this post I figured it out. parseInt(0.3) returns 0, therefore a 0.3%0 returns NaN because it results in a divide by zero.
I also noticed that I can not chain conditions in the following manner:
.filter(n => n>0 && n%parseInt(n) ? null : n)
This returns really weird values like this:
[ 9, 23.04, 25, 9, 10.240000000000002 ] for the first array of [-3, 4.8, 5, 3, -3.2]
Why does this conditional chain not work? does the use of the ternary operator void the “&&” ?
Okay holy duck, I think, again while writing, I figured it out. In this case the && does not mean “and” but it rather is the shorthand ternary that say “if the thing to the left is true, do the thing on the right” meaning if
n>0
is true it will do
n%parseInt(n
). But this in turn makes kinda little sense because thats the effect I want…kinda…no? I mean it is a filter function after all. This means it will execute the last statement in the chain, right? This means it will check n>0, and if thats true ( && ) it will try n%parseInt(n), if true return null, if false return the number n.
I can only guess that having a remainder of 0 does not result in a false?
I am sorry this got way more complicated than I anticipated. I hope I do not sound like a total idiot. My
Your code so far
const squareList = (arr) => {
// only change code below this line
let newArr
newArr = arr
.filter(n => n%parseInt(n) ? null : n)
.filter(n=> n>0)
.map(n=> n*n)
console.log(newArr)
return arr;
// only change code above this line
};
// test your code
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
.
Challenge: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
Link to the challenge: