Skip to content

Javascript array filter out numbers represented as strings

I have an array like this:

a = ["name","text","dog","1","2","cat"]

I want to filter out all the numbers represented as strings (integers and floats) from the above given array. In this case I want to filter out “1”, “2”

Desired Output


Note: I am looking for a clean and elegant way to solve this. A naive approach that comes to my mind is to try and typecast to a float (which would cover both integers and floats) and if it fails, only then I should include the element in the array. I was wondering if there is a better way to solve this.



You can iterate over the array using Array#filter and only keep the elements that are not numbers using isNaN:

const a = ["name","text","dog","1","2","cat",".2"];

const res = a.filter(isNaN);

User contributions licensed under: CC BY-SA
7 People found this is helpful