In example 1, the exclamation (!) is at the start of the punctuation array and does not get logged.
JavaScript
x
7
1
let lettersArray = ['h','i','!','$','%','#','"']
2
3
let punctuation = '!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~';
4
let filterPunc = lettersArray.filter((letter) => punctuation.indexOf(letter) > 0 )
5
console.log(filterPunc);
6
// ['$', '%', '#']
7
In example 2, the exclamation is somewhere else in the punctuation array and now gets logged.
JavaScript
1
5
1
let punctuation1 = '"#$%&!'()*+,-./:;<=>?@[\]^_`{|}~';
2
let filterPunc1 = lettersArray.filter((letter) => punctuation1.indexOf(letter) > 0 )
3
console.log(filterPunc1);
4
// ['!', '$', '%', '#']
5
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
.