Home > shorts > Coding filter() function with plain JavaScript
Coding filter() function with plain JavaScript
Coding filter() function with plain JavaScript
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
const juice = ["🧃🍏", "🧃🍎", "🍏", "🍎", "🍐", "🍊", "🧃🍐", "🧃🍊"]
const checkIfJuice = item => item.includes("🧃")
const isJuice = juice.filter(checkIfJuice)
isJuice // [ '🧃🍏', '🧃🍎', '🧃🍐', '🧃🍊' ]
Coding filter() function with plain JavaScript
const juice = ["🧃🍏", "🧃🍎", "🍏", "🍎", "🍐", "🍊", "🧃🍐", "🧃🍊"]
const checkIfJuice = item => item.includes("🧃")
const isJuice = newFilter(juice, checkIfJuice)
function newFilter(arr, conditionFunc) {
const filteredArr = []
for(let i = 0; i < arr.length; i++) {
conditionFunc(arr[i]) && filteredArr.push(arr[i])
}
return filteredArr
}
isJuice // [ '🧃🍏', '🧃🍎', '🧃🍐', '🧃🍊' ]