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) );
return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
I am not getting what is going in the code ? really depressed because in most of the challenges not able to write my own code. Please guide.
what is (num) inside the code ?
not able to understand the syntax of the code.
Why we use filter(), map(), reduce().
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
“use strict”;
/**
* const squaredIntegerst = arr.filter().map()
* // arr will be the array we enter into squareList()
* // .filter() will take a function that returns a value and return a new array with only that value
* // .map() will take the previous array and apply a function to each value in the array
*/
const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0
).map( (num) => Math.pow(num, 2) );
// arr.filter(function(num) {
// return num > 0 && num % parseInt(num) // num will be each value in arr
// })
// .map(function(){
// return Math.pow(num, 2) // apply this to each value in filtered array
// })
return squaredIntegers; // returns the new array that was filtered and mapped
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
we use map(), filter(), and so on for convenience. You can easily make your own functions that do the same thing but higher order function are ‘functions’ of Arrays that are built into JavaScript for easy use
see all array methods on the left - MDN
Here are some videos you can check out.