首页 > 解决方案 > 过滤数组后的原始索引位置

问题描述

我有一个根据用户在搜索框中输入的内容进行过滤的数组。

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]

我将如何实现这一目标?

标签: javascript

解决方案


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


推荐阅读