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