Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Check if an array element is a number

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?

like image 885
N. Levenets Avatar asked Aug 27 '26 08:08

N. Levenets


1 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'));
like image 196
CertainPerformance Avatar answered Aug 28 '26 22:08

CertainPerformance