Functional Programming - Solution with recursion: Implement the filter Method on a Prototype

Not a question but a hint: I saw a nice solution using recursion which used a growing integer (Alt. Solution and exercise ).

If anyone tries the same but wants to do it without passing a growing integer and more arrays, I added my solution below.

Array.prototype.myFilter = function(callback) {
let m = [1,2]

  if (this.length <= 1 ) {
    if (callback(this[0])) {
      return this[0]
    return [];
  if (callback(this[0])) {
    return [this[0]].concat(this.slice(1).myFilter(callback))
  return this.slice(1).myFilter(callback);


console.log([23, 65, 98, 5, 13,26].myFilter(item => item % 2))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36 Edg/107.0.1418.52

Challenge: Functional Programming - Implement the filter Method on a Prototype

Link to the challenge:

Thanks for sharing! Greatly appreciated! :blush:

Iā€™m not sure why I would want a recursive solution for this. This is just traversing an array. Recursion would probably be slower and use more memory.

Generally iterative solutions are more performant than recursive ones. Recursion has an advantage in readability if you are using reference linked structures (linked lists, trees, graphs, etc.)

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.