【问题标题】:How to search some text in an array and get the index of the searched array in javascript如何在数组中搜索一些文本并在javascript中获取搜索到的数组的索引
【发布时间】:2021-12-27 23:33:01
【问题描述】:
我想获取过滤后数组的索引
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'));
【问题讨论】:
标签:
javascript
arrays
string
filter
【解决方案1】:
您可以使用reduce。对于输入中的每个项目,如果它与给定的字符串匹配,则下面的代码会将其索引添加到数组中。
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'));
【解决方案2】:
您返回的是过滤后数组中的索引,而不是原始数组中的索引。
不要为此使用filter()。只需使用forEach(),将索引推送到结果中。
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'));