Why is output equal 2? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
20th Oct 2020, 10:12 AM
Тимур Завьялов
Тимур Завьялов - avatar
10 Answers
+ 1
Array <b> contains even elements filtered from array <c>, if you want you can log <b> in console, it contains 2 and 4.
20th Oct 2020, 10:23 AM
Ipang
+ 1
Ipang, please, can you explain and show how it works?
20th Oct 2020, 9:37 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
I don't understand
20th Oct 2020, 9:37 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
Ipang, if we remove "-1", then we get a uneven number? https://code.sololearn.com/Wan203cC14qV/?ref=app
21st Oct 2020, 6:37 AM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
Ipang, can I make it easier this way? https://code.sololearn.com/Wwx5YR3mu5G3/?ref=app
21st Oct 2020, 8:02 AM
Тимур Завьялов
Тимур Завьялов - avatar
0
* Create new array <c> containing 4 elements (1, 2, 3, 4) var c = new Array(1,2,3, 4); * Filter even numbers from array <c> into another array <c> using `filter` method of Array class. var b = c.filter (function (a) { return (a % 2 - 1); }); * To understand how `filter` method works please read this page 👇 // https://codeburst.io/useful-javascript-array-and-object-methods-6c7971d93230 * Display an alert dialog showing the first element of array <b>. alert(b[0]); * To see the whole array <b> do this instead. alert(b);
21st Oct 2020, 4:58 AM
Ipang
0
Yes, the `filter` method uses a predicate function, which accepts an argument (each of the array's elements). And the function is expected to return a boolean-like value (0 = false, other values = true). The value returned by the predicate function decides whether an element should be included in the filter result. `filter` method pass each array element as argument for the predicate function, one by one. If the predicate function returns true, the element given as argument will be included in the result. Otherwise, the element will not be included in the result (array <b>).
21st Oct 2020, 7:40 AM
Ipang
0
Now let's see what happens in the predicate function with array <c> content [ 1, 2, 3, 4 ] <a> = 1 1 % 2 yields 1, subtract by one => 0 means return false (1 will be excluded from result) <a> = 2 2 % 2 yields 0, subtract by one => -1 means return true (2 will be included in result) <a> = 3 3 % 2 yields 1, subtract by one => 0 means return false (3 will excluded from result) <a> = 4 4 % 2 yields 0, subtract by one => -1 means return true (4 will included in result)
21st Oct 2020, 7:43 AM
Ipang
0
Yes, that can do as well 👍
21st Oct 2020, 8:52 AM
Ipang
0
i don’t know much about algebra, but i know 1 + 1 = 2!!!!!
23rd Oct 2020, 1:52 AM
SappyB
SappyB - avatar