Eddie Lam
Eddie Lam

Reputation: 619

Check if an array includes some special characters

I am trying to check if a password string contains some special characters.
I am trying to implement that with the following code:

const passwordArr = "A1b2c3d4e5!@#".split("");
const specialChar = "~!@#$%^&*_-+=`|(){}[]:;\"'<>,.?/";
const hasSpecLet = passwordArr.some((letter) => {
  specialChar.includes(letter);
});

However, hasSpecLet returns false.

Upvotes: 3

Views: 1944

Answers (5)

Ajeet Eppakayala
Ajeet Eppakayala

Reputation: 1435

whenever you are using { } inside an arrow function you have to use return keyword O.W. values are returned by default.

const passwordArr = "A1b2c3d4e5!@#".split("");
const specialChar = "~!@#$%^&*_-+=`|(){}[]:;\"'<>,.?/";
const hasSpecLet = passwordArr.some((letter) => {
   return specialChar.includes(letter);
});
console.log(hasSpecLet);

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28424

You need to use return since the arrow function uses curly braces:

const passwordArr = "A1b2c3d4e5!@#".split("");
const specialChar = "~!@#$%^&*_-+=`|(){}[]:;\"'<>,.?/";
const hasSpecLet = passwordArr.some((letter) => {
  return specialChar.includes(letter);
});
console.log(hasSpecLet);

Or do the following:

const passwordArr = "A1b2c3d4e5!@#".split("");
const specialChar = "~!@#$%^&*_-+=`|(){}[]:;\"'<>,.?/";
const hasSpecLet = passwordArr.some((letter) => 
  specialChar.includes(letter)
);
console.log(hasSpecLet);

Upvotes: 0

Anup
Anup

Reputation: 629

Using some() and include()

const hasSpecLet  = passwordArr.some((letter) => specialChar.includes(letter))

Using intersection

const hasSpecLet = passwordArr.filter(value => specialChar.split('').includes(value)).length !== 0 

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

This small change will make it work -

const passwordArr = "A1b2c3d4e5!@#".split("");
const specialChar = "~!@#$%^&*_-+=`|(){}[]:;\"'<>,.?/";
const hasSpecLet = passwordArr.some((letter) => 
  specialChar.includes(letter)
);

console.log(hasSpecLet)

The above change will make sure that the value processed by - specialChar.includes(letter) gets returned and used in the parent function to give the final result.

In your case, none of the letters returned a true value and hence you would have got false in every case

Upvotes: 0

haim770
haim770

Reputation: 49115

You're missing the return statement in the function you're passing to some():

const hasSpecLet = passwordArr.some((letter) => {
  return specialChar.includes(letter);
});

Or just use a terser version (without the curly braces):

const hasSpecLet = passwordArr.some(letter => specialChar.includes(letter));

See MDN

Upvotes: 2

Related Questions