In example 1, the exclamation (!) is at the start of the punctuation array and does not get logged.
let lettersArray = ['h','i','!','$','%','#','"']
let punctuation = '!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~';
let filterPunc = lettersArray.filter((letter) => punctuation.indexOf(letter) > 0 )
console.log(filterPunc);
// ['$', '%', '#']
In example 2, the exclamation is somewhere else in the punctuation array and now gets logged.
let punctuation1 = '"#$%&!'()*+,-./:;<=>?@[\]^_`{|}~';
let filterPunc1 = lettersArray.filter((letter) => punctuation1.indexOf(letter) > 0 )
console.log(filterPunc1);
// ['!', '$', '%', '#']
I believe it’s being interpreted as a logical-not-operator but I’m unsure why since I would assume the quotation marks would make it a string.
Advertisement
Answer
Instead of punctuation.indexOf(letter) > 0 you shall use punctuation.indexOf(letter) >= 0 or better punctuation.includes(letter).
If you use > instead of >= the first element which has index 0 would get excluded.
And nevertheless indexOf returns -1 for non existing elements, not 0.