+ 2

Help please

Can someone help me with this...? nums.filter(n => n % 2 == 0).map(el => sum+= el); I don't understand, I'm in JS' rest parameter lesson, but there does not explain what in this line are

17th Aug 2020, 5:00 PM
Bry4n
Bry4n - avatar
5 odpowiedzi
+ 6
Look, i m gonna tell using simple function syntax, not arrow functions, to make things clear. Here's an array let array = [ 1, 2, 3, 4, 5 ] Now I just wanna get an array with numbers ABOVE 2, so i would filter this array. array.filter() Now this filter takes something between those brackets, that something means "parameter" it takes a function as a parameter. array.filter(function() { }) Now i wanna give a name so that i can refer to each single number inside of this array, i will just call it "number" array.filter(function(number) { } ) Now inside the curly brackets, i will RETURN the numbers that are above 2, so, array.filter(function(number) { return number > 2 }) You can store the result inside a variable Now that u know filter(), map() doesnt filter an array it just simply goes through an array and returns a new array, such as if u want to double each element inside an array let array = [ 1, 2, 3, 4, 5 ] let doubledArray = array.map( function (num) { return num * 2 }) // [2,4,6,8,10]
17th Aug 2020, 6:22 PM
maf
maf - avatar
+ 5
Bryan Martinez it literally made me smile :D im glad i could help
17th Aug 2020, 6:36 PM
maf
maf - avatar
+ 2
This is all the code function magic(...nums) { let sum = 0; nums.filter(n => n % 2 == 0).map(el => sum+= el); return sum; } console.log(magic(1, 2, 3, 4, 5, 6));
17th Aug 2020, 5:01 PM
Bry4n
Bry4n - avatar
+ 2
... parameter packs the arguments into an array and nums.filter(n=>n%2==0).map(el=>sum+=el) is chaining of different methods so now filter returns an array which contains the elements whose remainder was 0 and then those elements are added together using map
17th Aug 2020, 5:35 PM
Abhay
Abhay - avatar
+ 2
@maf seriously thank you very much, you born to teach, 'cause now I already understand each character, thanks.
17th Aug 2020, 6:35 PM
Bry4n
Bry4n - avatar