Tell us what’s happening:
Hello,
My logic in the code below was to return a filtered array of positive integer values, once that happened the plan was to filter it again using an sqrt(value) function. The problem is the second filter is ignored entirely, only returning the array that the first filter provides. Can someone please help me figure out what went wrong?
**Your code so far**
function isIntegerAndPositive(number) {
if ( Number.isInteger(number) && number > 0) {
return number;
}
}
const squareList = arr => {
return (arr.filter(isIntegerAndPositive)).filter( value => Math.sqrt(value));
};
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
**Your browser information:**
User Agent is: Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0.
Challenge: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
Not necessarily it get’s ignored. filter method filters out element if it passed to the filtering function returns value evaluating to false. First filter is supposed to filter numbers that are not integer or not positive. Taking a look at the function passed to second filter - what number would need to be passed into it, so Math.sqrt() function would return value evaluating to false?
I do not have the solution yet, but at least I understand the problem now. The second filter will never evaluate anything to false, so it will return everything from the first array.
Ok. I got it. So first of all, I was using sqrt which is square root. The challenge asks for square of the number. With that out of the way, I just used map instead of the second filter and it works. This is how the code looks now:
function isIntegerAndPositive(number) {
if ( Number.isInteger(number) && number > 0) {
return number;
}
}
const squareList = arr => {
return (arr.filter(isIntegerAndPositive)).map( value => value * value);
};
I’m not sure what you mean. Can you please elaborate? Edit
I think you are referring to the line return number
Is the edited code below better suited for most cases?
function isIntegerAndPositive(number) {
if ( Number.isInteger(number) && number > 0) {
return true;
}
}
if you had to keep the number 0 in your code it would be filtered instead.
try this for example in which we want to keep only integers (all, not only positive)
let output = [0, 4.5, 1, 0, -1].filter(function (number) {
if ( Number.isInteger(number)) {
return number;
}
}
if you check the value of the output the number 0 is missing, even if ti is an integer. That’s because 0 is a falsy value, and it is filtered out. The callback needs to return true or false, not what you want to keep