I am working through freecodecamp.org's Javascript ES6 coding problems and one of them tasked me with using arrow function notation to:
- Take an array of real numbers.
- Filter only the positive integers into a new array, and
- Square those positive integers.
I have successfully completed the problem but built my code for Step 2 by filtering the original array with Numbers.isInteger(). Freecodecamp.org's provided answer utilizes parseInt().
I do not see why we would need to parse integers if they are already integers, nor why parseInt() does not throw an error since its parameter asks for a string.
My primary question: Are both equally acceptable? Is one going to get me into more trouble down the road?
The only closely relevant stackoverfow I found was here (which was vaguely helpful). Below is my code followed by the answer code provided by freecodecamp.org. NOTE: I am aware my code has a few extra steps in it. I am not a huge fan of arrow notation and am still improving my code-organization!
MY CODE::
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
// dictates what numbers are filter()'d out of original array
const checkElement = (value) => value > 0 && Number.isInteger(value) == true;
const integersOnly = arr.filter(checkElement); //filters ONLY positive integers into new array
PROVIDED ANSWER CODE::
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );