2022-12-12

 12 Dec 2022

Implementing Array.filter() via Array.forEach()

JavaScript provides the very useful Array.filter() method for extracting elements from an array that match an input condition, and this behavior can be replicated using the Array.forEach() method as well:

function filter(arr, callback) {
  const result = []
  arr.forEach(element => {
     if (callback(element)) {
      result.push(element)
    }
  })
  return result
}

Where the arr argument is the array, and the callback argument represents the conditional expression to be evaluated for each item:

filter([1, 2, 3], num => num >= 0) // [1, 2, 3]

filter([1, 2, 3], num => num > 5) // []

#TIL #TheMoreYouKnow

Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

this node is permanently morphing last updated on 26 Dec 2022

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #TIL