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);
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With