Filter() and map() not working on this specific problem

Tell us what’s happening:

Alright, as far as I can tell, this code should be working. However, on this particular page, .filter() and .map() do not behave as I normally expect them to.
Input: [-3, 4.8, 5, 3, -3.2]
Output: [ -3, 4.8, 5, 3, -3.2 ]

Your code so far


const squareList = (arr) => {
// Only change code below this line

/* 
To return an array of squared integers,
  filter non-positive non-integers,
  map those integers with a square.
*/ 
arr
  .filter(num => num > 0 && Number.isInteger(num))
  .map(int => Math.pow(int, 2));

return arr;
// Only change code above this line
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15.

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

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem

the thing is that they return a new array, do not change the array they are used on.

And you do nothing with the returned value. You are not even storing it anywhere.

Meanwhile, arr is unchanged

1 Like

Map and Filter do not mutate arrays. That’s the whole point of them.
The verbatim Solution #1 listed is:

const squareList = arr =>
  arr
    .filter(num => num > 0 && num % parseInt(num) === 0)
    .map(num => Math.pow(num, 2));

This does not work either. I ended up just copy-pasting the second solution, which utilizes .reduce()

EDIT: Wait, I see what you mean. That must be it.

exactly, you have

arr.filter(...).map(...);
return arr;

the array is not mutated, but the returned array is not used either
you have written a piece of code that does nothing.

I see your edit, hope you saw it

1 Like

Once I understood what you meant, I just put a return in front of all that. Thanks!

return arr
  .filter(num => num > 0 && Number.isInteger(num))
  .map(int => Math.pow(int, 2));
1 Like