Reputation: 87
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?
Upvotes: 3
Views: 17225
Reputation: 33726
You're trying to access an index using the numbers, change to this:
let newArray = arr.filter((c) => !isNaN(parseInt(c)));
^
Further, you need to use the array which is returned by the function filter
.
Upvotes: 1
Reputation: 370759
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'));
Upvotes: 7