Help please | Sololearn: Learn to code for FREE!


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

8/17/2020 5:00:53 PM


5 Answers

New Answer


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 = function (num) { return num * 2 }) // [2,4,6,8,10]


Bryan Martinez it literally made me smile :D im glad i could help


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));


... 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


@maf seriously thank you very much, you born to teach, 'cause now I already understand each character, thanks.