1

I am trying to check all the element type of an array in javascript. I am actually writing a function which whould only accept an array with numbers.

so

[1,2,-3,-4,0]  //valid input
[1,2,-3b,-4a,0]  //Invalid input

I am trying to achieve the following by using every() function of javascript as follows,

try {
                    if (!inputArr.every(x => typeof x === 'number')) {
                           throw 'input array should only have numbers';
                    }
                }
                catch (err) {
                    return err;
                }

but getting error. when I investigate it further than realized that,

typeof 1 // number
typeof 1a // error

so there is no way we can check the type of a alphanumeric value. can someone please suggest some options here. I am using pure javascript ES5 Or ES6.

9
  • you can also use isNaN() Commented Jun 29, 2017 at 1:19
  • @Manatax But isNaN("123") would return false, even though "123" is not a number. If that suits OP's needs, then it would work. If the goal is a stricter check, then typeof seems like the way to go. Commented Jun 29, 2017 at 1:21
  • @Manatax, I need to check strictly that supplied input array has all the numbers ONLY. isNan will not work here as mentioned by @ Michael Geary Commented Jun 29, 2017 at 1:50
  • Since [1,2,-3b,-4a,0] is invalid syntax, and your program would not even run, should we assume that the input is a kind-of array represented as a string, as in "[1,2,-3b,-4a,0]"? Commented Jun 29, 2017 at 2:42
  • 1
    @Akash Wait, are you saying the input to your function is a string, not an array, and the string may be something like "[1,2,-3a,4]"? That is a whole different question. I would first use JSON.parse() to attempt to convert this string to a JavaScript array. If it throws an exception, then you had something like the "-3a" in it and should reject. Otherwise, run your test loop on the resulting array. Commented Jun 29, 2017 at 4:15

1 Answer 1

2

[1,2,-3b,-4a,0] is invalid syntax, and your program would not even run. Therefore, we will assume that the input is a string, as in "[1,2,-3b,-4a,0]". In that case:

function check(input) {
  try {
    const array = JSON.parse(input);
    return array.every(x => typeof x === 'number');
  } catch(e) {
    return false;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.