Question about filter method

let arr = string.split(" ").map(it => parseInt(it.replace(/[^01]/g, ''), 2)).filter(Number);

I don’t understand why is Number passed inside filter.

Shouldn’t we write it like this?

.filter(num => typeof num == "number");

Can someone explain I would be grateful?

It’s hard to tell the point of this without more context, but if you expand it a bit:

let arr = string
    .split(" ")
    .map((it) => {
      console.log(it);
      it = parseInt(it.replace(/[^01]/g, ''), 2);
      console.log(it);
      return it;
    })
    .filter(Number);

it may help you see what’s happening. filter() just evaluates its function and returns the array value on truthy, or null otherwise. So if it is parsable as a binary number, then it is not filtered out. If not, map() returns a falsy it, which filter() rejects.

1 Like

This is speculation, but what I imagine is happening is that you are handing filter the Number constructor which is then being called with the elements of the array, and I would think this is done because the array is filled with strings, and this '0' is a truthy value whereas this 0 is not, and I do not no the context of the problem, but that would indicate that you do not want zeros. You can realistically pass any function for a callback, but I would not have though of writing it the way it was, but for clarity this i the same thing

console.log(['1', '0', '3'].filter(Number)); ///["1", "3"]

console.log(['1', '0', '3'].filter(e => Number(e))); //["1", "3"]
1 Like

Yeah my bad for not providing more context, here it is

And this is my solution

function chuckPushUps(s) {
  
  if (!s || typeof(s)!='string') return 'FAIL!!';
  if (!s.includes('0')&&!s.includes('1')) return 'CHUCK SMASH!!';
  
  const arr = s.split(' ').map(el => parseInt(el.replace(/[^01]/g, ''), 2)).filter(Number);
  return Math.max(...arr);
}

Your solution will fail in the case of chuckPushUps('0LGf0jc8aKePs') because using the filter method with Number as the callback function produces Infinity for the value for the mapped array [0]. You can use a filter callback that checks if the number is greater or equal to 0 and return 0 for this string.

1 Like

Thank You Sir for explaining it to me.