I learn js and trying to write filter method without using it. So I need to my function return filtered array based on function, which passed as a parameter. And it does but it’s returned boolean array and I don’t understand why.
My code:
function myFilter(arr, func) { const result = []; for (let el of arr) { result.push(func(el)); } return result; }
Calling with some numbers:
myFilter([2, 5, 1, 3, 8, 6], function(el) { return el > 3 })
It should’ve returned [5, 8, 6] but instead I got [false, true, false, true, true]. I don’t get why can someone please explain it to me?
Advertisement
Answer
It’s returning a boolean array because you’re pushing booleans into the result
array. func(el)
or function(el) { return el > 3 }
returns a boolean.
What you want is to push elements/numbers into the result
array based on the condition of func(el)
Try
function myFilter(arr, func) { const result = []; for (let el of arr) { if (func(el)) { result.push(el); } } return result; }