Array.filter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Array.filter

Can someone please explain this? var c = new Array(1, 2, 3, 4); var b = c.filter(function(a) { return (a % 2 - 1); }) alert(b[0]); // 2 Why is the result 2?

13th Apr 2022, 5:36 AM
David
David - avatar
5 Answers
+ 3
filter() method does not execute the function for empty elements. 1%2-1 = 0(an empty value) 2%2-1 = -1(not an empty) So, it returns the even numbers from array c hence, 2 is the first element.
13th Apr 2022, 6:04 AM
Simba
Simba - avatar
+ 3
filter() method iterates an array, invokes an aggregate function on each iteration, passing one array element to the aggregate function at a time (sequentially). An element passes the qualification when the aggregate function, being invoked with the element as argument (here represented by <a>), returns truthy value. + An element that passes the qualification will be included in filtered array. <a> = 1 (1st element) a % 2 - 1 evaluates as ((1 % 2) - 1), resulted as 0 (1) doesn't pass the test (zero is falsy) <a> = 2 (2nd element) a % 2 - 1 evaluates as ((2 % 2) - 1), resulted as -1 (2) passes the test (-1 is truthy) <a> = 3 (3rd element) a % 2 - 1 evaluates as ((3 % 2) - 1), resulted as 0 (3) doesn't pass the test (zero is falsy) <a> = 4 (4th element) a % 2 - 1 evaluates as ((4 % 2) - 1), resulted as -1 (4) passes the test (-1 is truthy) The array returned by filter() method is [ 2, 4 ]. Being subscripted with index 0, the 1st element (2) will be displayed in the alert() box.
13th Apr 2022, 8:03 AM
Ipang
+ 2
David, Very welcome My pleasure 👌
13th Apr 2022, 2:08 PM
Ipang
+ 1
Ipang very well explained, thanks a lot for your time :)
13th Apr 2022, 2:07 PM
David
David - avatar
0
Simba thanks.
13th Apr 2022, 2:07 PM
David
David - avatar