DEV Community

Randy Rivera
Randy Rivera

Posted on

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

  • Now that you have worked and looked through the posts using higher-order functions like map(), filter(), and reduce(), you now get to apply them to solve a more complex challenge.

  • Complete the code for the squareList function using any combination of map(), filter(), and reduce(). The function should return a new array containing the squares of only the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array of real numbers is [-3, 4.8, 5, 3, -3.2].

const squareList = arr => {
  // Only change code below this line
  return arr;
  // Only change code above this line
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
Enter fullscreen mode Exit fullscreen mode
  • Hint:
  • You will need to filter() the squareList for positive integers (decimals are not integers) and you will need to map()the values from your filter() function to a variable.
  • Answer:
const squareList = arr => {
  let positiveIntegersSquared = arr.filter(num => {
    if (Number.isInteger(num) && num > 0) {
      return num;
    } 
  })
    .map(num => {
      return num * num
  });

  return positiveIntegersSquared;
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
Enter fullscreen mode Exit fullscreen mode
  • squareList([-3, 4.8, 5, 3, -3.2]) should return [25, 9].

Top comments (0)