Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - every() method to check isInteger on array elements

I want to check return true if an array contains all integers or false if not. I am trying to use the every method MDN docs every.

So if given '1234' it will return true and if given '123a' it would return false.

  function validatePIN (pin) {
    pinArray = pin.split("");
      if (pinArray.length === 4 || pinArray.length === 6) {
        if (pinArray.every(Number.isInteger()) === true;) {
          return true
    }};

How does every pass the element to isInteger so it can test it?

like image 201
sayth Avatar asked May 29 '26 16:05

sayth


2 Answers

Even if you fix syntax error and pass Number.isInteger as a function this won't work.

function wrongValidatePIN (pin) {
    var pinArray = pin.split(""); // <-- array of strings
      if (pinArray.length === 4 || pinArray.length === 6) {
        if (pinArray.every(Number.isInteger)) { // <-- isInteger works with numbers
          return true
    }}
    return false
}

console.log(wrongValidatePIN('1234'))

You need something like this

    function validatePIN (pin) {
        var pinArray = pin.split(""); // <-- array of strings
        
        return (pinArray.length === 4 || pinArray.length === 6)
           && pinArray.every(char => !Number.isNaN(Number.parseInt(char, 10)))
    }

    console.log(validatePIN('1234'), validatePIN('123a'))

Or you could use regexp

function validatePin(pin) {
  return /^(\d{4}|\d{6})$/.test(pin)
}

console.log(validatePin('1234'), validatePin('123456'),
 validatePin('12345'), validatePin('123a'))
like image 98
Yury Tarabanko Avatar answered May 31 '26 06:05

Yury Tarabanko


As the comments stated, the isInteger function can be passed as an argument by calling pinArray.every(Number.isInteger) instead of calling it a single time, (or by providing it inside a function .every(c=>Number.isInteger(c)) , but passing the function itself is more concise)

However, it's unlikely to provide the result you expect, because isInteger checks if the value is an actual integer, not if the value can be parsed to one.

That could be resolved with something like pinArray.map(parseFloat).every(Number.isInteger);

but then it would be easier to use !pinArray.some(isNaN)

That could make the function:

function validatePIN (pin) {
    return (pin.length === 4 || pin.length === 6) 
        && ![...pin].some(isNaN);
}

But as a final note, regular expressions are made for this type of check and could be preferable here

like image 41
Me.Name Avatar answered May 31 '26 04:05

Me.Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!