I’m doing ‘ES6: Write Higher Order Arrow Functions’ in JavaScript Data Structure and Algorithms Certifications.
It asks to use arrow functions to filter an array to integers (new array is squaredIntegers), which I did, and then square them. I have tried: console.log(squaredIntegers.map((squaredIntegers) => squaredIntegers.sqr)
Here is my code so far:
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
var squaredIntegers =[];
// change code below this line
squaredIntegers.push( arr.filter( (arr) =>arr%1==0) )
;console.clear(squaredIntegers);
console.log(squaredIntegers);
console.log( squaredIntegers.map((squaredIntegers)=>squaredIntegers*squaredIntegers));
// change code above this line
return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
first thing, map will not work as you wish because you are pushing an array inside squareIntegers - do you need push here? can’t you just do assignment with =?
(@DanCouper is right, I was wrong with the filter comment)
Filter creates a new array. So the squaredIntegers array after the push looks like [[n,n,n,n...]]; you’re pushing an array into an array.
Console log just logs a value, it doesn’t return anything.
Because the only value in squaredIntegers is another array, your map won’t work because you’re trying to multiply an array and an array.
If you fix this, map creates a new array. So squaredIntegers.map... will indeed perform a map across the array, but squaredIntegers will still remain the same, and that’s what you’re returning
Edit: afaics the filter function is almost fine @ilenia – n % 1 == 0 tests whether a number is an integer. Needs to also check the number is positive as well, but it doesn’t always return true.