Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

try

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') > -1;
  
});
about 4 years ago · Juan Pablo Isaza Report

0

String.prototype.indexOf(searchString, position) takes two arguments:

  1. First is the substring that needs to be searched.
  2. 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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!