javascript - 过滤数组后的原始索引位置
问题描述
我有一个根据用户在搜索框中输入的内容进行过滤的数组。
var x = ["Apple","Pear","Pineapple"];
var value = e.target.value;
var regex = new RegExp(`^${value}`, 'i');
var filtered = x.sort().filter(v => regex.test(v));
如果我在搜索框中输入“P”,控制台会打印
["Pear","Pineapple"]
然而,我需要的是梨和菠萝的原始索引位置的另一个数组,它将打印以下内容
[1,2]
我将如何实现这一目标?
解决方案
Instead of filtering the array, filter
the keys
of the array instead:
var x = ["Apple","Pear","Pineapple"],
value ="P",
regex = new RegExp(`^${value}`, 'i'),
filtered = [...x.keys()].filter(i => regex.test(x[i]));
console.log(filtered)
keys()
method returns a Array Iterator. So, you need to use spread syntax or Array.from()
to convert it to an array
推荐阅读
- android - 运行 git cloned android 项目时出错
- php - Laravel 雄辩的变异器不适用于更新数据
- java - 嵌套 JSON 的问题
- javascript - 在javascript中获取所选关键字之前的所有字符
- html - 固定位置在任何浏览器中都不起作用
- javascript - jquery使用for循环和随机eq触发多次点击事件
- android - 为什么 Retrofit 的 onResponse 方法没有运行?
- python - 为python中的每个唯一值在多行中搜索多个值
- java - 无法写入 HTTP 消息:org.springframework.http.converter.HttpMessageNotWritableException:无法写入 JSON:错误
- asp.net-core - asp.net-core,使用特定的编码名称