1

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

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

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.

0

1 Answer 1

3

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);

console.log(res);

Sign up to request clarification or add additional context in comments.

6 Comments

Great, this works! Can you explain a little as to why?
My use case was for numbers and that is what I intended, sorry for the confusion. I can edit the Question to make that clearer
isNaN('2005/12/12') //true what do you think? you says?
Number.isInteger('2005/12/12'); //false, what do you mean integer?
@SeniorWebEngineer this value is not a number, neither an integer. Can you clarify your question?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.