I have an array of arbitrary elements and need to get only number elements.
I tried arr.filter((c) => !isNaN(parseInt(arr[c]))); but that didn't work. I still have a full array. What is wrong here and what else can I do?
2 Answers
The first argument in the callback to .filter is the array item being iterated over - if c is the array item, then referencing arr[c] usually doesn't make much sense. Try using a simple typeof check instead:
const arr = [3, 'foo', { bar: 'baz' }, false, 4, 5];
console.log(arr.filter(item => typeof item === 'number'));
cis the valuearr[c]is not defined.parseIntcheck is going to include strings that only start with digits. If the array elements are JavaScript numbers, you just needtypeof; if you want to check for strings of a particular format, I’d recommend a regular expression.