Write Higher Order Arrow Functions ES6

Tell us what’s happening:
I dont seem to understand why squaredIntegers doesnt not return [16, 1764, 36]. Its returning [ 4, 42, 6 ]

Could someone please help me understand where I’m going wrong?

Your code so far


const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";
  // change code below this line
  const squaredIntegers = arr.filter((val) => {
    if(val > 0 && Math.floor(val) == val && Math.ceil(val) == val) {
      return val * val;
    }
  });
  // change code above this line
  return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions/

1 Like

You aren’t using filter correctly. All filter does is remove values from an array. Any time the filter function does not return a truthy value, the array item is removed. If it returns a truthy value, then the array item stays (and is not changed).

You may want to look at array.map().

To get some idea, what we are talking about:

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];

// filter the array
const filteredArray = realNumberArray.filter(
  n => n > 0 && Math.floor(n) == n && Math.ceil(n) == n
);
console.log(filteredArray);

// map the array
const squared = filteredArray.map((n) => n ** 2);
console.log(squared);

You can try to implement these two steps into one.

Much more readable and understandable solution:

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];

const squareList = (arr) => {
  'use strict';
  
  const squaredIntegers = arr
  // filter the array with built-in function
    .filter((m) => Number.isInteger(m))
  // return for every filtered value new value
    .map((n) => n ** 2);

  return squaredIntegers;
};

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

And a last, shortened version:

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];

const squareList = (arr) => arr.filter((m) => Number.isInteger(m)).map((n) => n ** 2);

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
2 Likes

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

3 Likes

Thanks. Helped me clear up some concepts.