I have an array of strings that I am wanting to filter.
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
I am wanting to keep only the words that include the letter ‘a’.
var wordsWithA = words.filter(function (word) {
return words.indexOf('a', 4);
});
how do you accomplish this using indexOf in javascript?
>Solution :
indexOf
returns -1
, if it doesn’t find the element in the container. You should use indexOf
on each string word
and not on the array words
:
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
return word.indexOf('a') !== -1;
});
console.log(wordsWithA);