DEV Community

Let's create our own filter method in JS

machy44 on February 26, 2018

JS is a prototype-based language which means that if we create an array variable, it's prototype is Array.prototype. Every array inherits the metho...
Collapse
 
sektor001 profile image
Sektor001

Why do you have (this[i], i, this) in the if statement? dont you only need this[i]?

Collapse
 
santoshah profile image
Santosh

I was thinking same. In this context we would need only this[i] but we are trying to create a generic function that does more than just a filter. By passing index and entire array we can also get specific position element. This is what I have understand.

Collapse
 
machy44 profile image
machy44

You were right. Sorry I didnt see your comments before

Collapse
 
nestedsoftware profile image
Nested Software

Cool! It's funny, I was just inspired to write my first post about a 'lazy' version of 'map' and 'filter' in JavaScript!

Collapse
 
machy44 profile image
machy44

That's great! :) It seems very interesting. I will take a look on your post.

Collapse
 
abidemit profile image
Tiamiyu Sikiru Abidemi

Thanks... quite easy to understand.

Collapse
 
kingjofr profile image
KingJoFr

if (fun(this[i], i, this)) filtered.push(this[i]);

In this line why are there no curly braces around filtered.push(this[i]); ?

like this:

if(fun(this[i], i, this)) {
filtered.push(this[i]);
}

Collapse
 
machy44 profile image
machy44

syntax is not important here. I believe that today I would write it with curly braces.