DEV Community

Discussion on: Build Your Own Filter

Collapse
 
aminnairi profile image
Amin • Edited

Hi there, thanks for your article. I liked the fact that you gave multiple ways of doing this filter function.

I'm not sure if this was intended, but you didn't give any code example for the recursive solution. Here is my take.

const filter = (shouldBeKept, items) => {
    if (items.length === 0) {
        return [];
    }

    const [item, ...rest] = items;

    if (shouldBeKept(item)) {
        return [item, ...filter(shouldBeKept, rest)];
    }

    return filter(shouldBeKept, rest);
};

If we break it down:

  1. We first check if we didn't receive an empty array (this is our base-case for our recursive function to stop)
  2. If this is the case, we stop here and return an empty array as well
  3. Otherwise, we destructure our array to get the first item and the rest
  4. We check if we should keep the first item or not
  5. If this is the case, then we return an array concatenating the first item and we filter out the rest
  6. Otherwise, we just continue on filtering the rest and we return the result of this recursive call
  7. Again, the function is recursive, so this means that it will go back to the first step

What do you think?

Collapse
 
kasrakhosravi profile image
Kasra Khosravi

Thanks Amin for letting me know :) I forgot to put the snippet code in the blog post. I just updated it.

I like your approach; it is very readable and understandable.