Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Higher Order Functions : Array Filter JavaSctipt

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading