Home > Blockchain >  Why function returns filtered boolean array
Why function returns filtered boolean array

Time:08-24

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?

CodePudding user response:

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;
}

CodePudding user response:

Better use the javascript inbuit filter func, you dont need one of your own:

const filtered = [2, 5, 1, 3, 8, 6].filter(el => el > 3) 
console.log(filtered)

CodePudding user response:

1st You need to return after the condition true or false, Ex. For in your case,

myFilter([2, 5, 1, 3, 8, 6], function(el) { return  el > 3 && el  });

2nd You need to check wether the values true or not, For Ex. in your case,

for (let el of arr) {
  if (func(el))
    result.push(func(el));
  }
}
  • Related