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?
CodePudding user response:
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);
CodePudding user response:
try
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
return word.indexOf('a') > -1;
});
CodePudding user response:
String.prototype.indexOf(searchString, position) takes two arguments:
- First is the substring that needs to be searched.
- Second is an optional argument, that is the position from where the substring needs to be searched, the default value of which is
0
.
And the method returns the index of the first occurrence of the searchString
, if found, and returns -1
otherwise.
In your case you can omit the position
argument and do it as follows:
const words = ["hello", "sunshine", "apple", "orange", "pineapple"],
wordsWithA = words.filter((word) => word.indexOf("a") !== -1);
console.log(wordsWithA);