Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce vs Filter and Map

Tags:

javascript

I've written a function that computes the square of only the positive integers in the array realNumberArray and returns a new array with the result.

example: [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2] returns [16,1764,36]

How would you recreate the following function using only reduce() and what would be the preferred way?

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
  const squaredIntegers = arr;
  let newArr=squaredIntegers.filter(val=>val%1==0 && val>0).map(val=>Math.pow(val,2))
  return newArr;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
like image 987
Boris Aronson Avatar asked Oct 17 '22 05:10

Boris Aronson


1 Answers

You can do it like this with reduce:

const squareList = arr =>
  arr.reduce((out, x) => x % 1 === 0 && x > 0 ? [...out, x * x] : out, []);

console.log(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]));
like image 122
jo_va Avatar answered Nov 03 '22 18:11

jo_va