Home > Software design >  How to search some text in an array and get the index of the searched array in javascript
How to search some text in an array and get the index of the searched array in javascript

Time:11-17

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'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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'));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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'));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related