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

147
Views
How to search some text in an array and get the index of the searched array in javascript

I want to get the index of filtered array

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  const result = [];
  arr.filter(fruit => fruit.match(searchtxt)).forEach((element, index) => {
    result.push(index);
  });
  return result;
}

console.log(customFilter(arr, 'ma'));

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

0

You can use reduce. For each item in the input, the code below adds its index to an array if it matches the given string.

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  return arr.reduce((a, c, i) => c.match(searchtxt) ? [...a, i] : a, [])
}

console.log(customFilter(arr, 'ma'));

about 4 years ago · Juan Pablo Isaza Report

0

You're returning the index in the filtered array, not its index in the original array.

Don't use filter() for this. Just use forEach(), pushing the index into the result.

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  const result = [];
  arr.forEach((fruit, index) => {
    if (fruit.match(searchtxt)) {
      result.push(index);
    }
  })
  return result;
}

console.log(customFilter(arr, 'ma'));

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!